Skip to content

[ci] Add a docstring-only label that runs only the changed modules' docstring examples, piloted on Ray Data - #66814

Merged
dstrodtman merged 6 commits into
masterfrom
doc-1754-docstring-only-label
Oct 14, 2026
Merged

dstrodtman merged 6 commits into
masterfrom
doc-1754-docstring-only-label

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

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.
    2. 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.
    3. 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 and 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

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

@dstrodtman dstrodtman changed the title [ci] Add a docstring-only label that skips Ray Data test suites for docstring-only PRs [ci] Add a docstring-only label that runs only the changed modules' docstring examples, piloted on Ray Data Oct 7, 2026
@dstrodtman
dstrodtman added this pull request to stack #66819 October 7, 2026 19:57
@dstrodtman
dstrodtman marked this pull request as ready for review October 8, 2026 13:44
@dstrodtman
dstrodtman requested review from a team as code owners October 8, 2026 13:44

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a "docstring-only" label workflow for Ray Data, allowing Buildkite to skip full test suites and instead run only the docstring examples in changed modules, verified by an AST-based scope guard. The review feedback focuses on improving the robustness and cross-platform compatibility of these new scripts. Key recommendations include running docstring examples directly in the module's globals (with proper cleanup) to support mocks, handling multi-line exceptions, using cross-platform path normalization, dynamically resolving git remotes (e.g., "upstream" vs "origin") for fork developers, adding a "--base" CLI argument for local testing, and specifying UTF-8 encoding when opening files.

Comment on lines +107 to +147
def run_docstring(
docstring: DocstringExamples, module_globals: Dict, filename: str
) -> Optional[str]:
"""Run one docstring's examples in order. Return a report on failure."""
checker = doctest.OutputChecker()
namespace = dict(module_globals)
for example in docstring.examples:
if example.options.get(doctest.SKIP):
continue
# example.lineno counts from the docstring's first line.
line = docstring.lineno + example.lineno
location = f"{filename}:{line} ({docstring.qualname})"
flags = _optionflags(example)
stdout = io.StringIO()
try:
# "single" mode echoes an expression's value, as the interactive
# prompt the example imitates does.
code = compile(example.source, location, "single")
with contextlib.redirect_stdout(stdout):
exec(code, namespace)
except BaseException as e: # noqa: BLE001 - report any failure.
if example.exc_msg is not None:
got = traceback.format_exception_only(type(e), e)[-1]
if checker.check_output(example.exc_msg, got, flags):
continue
return (
f"{location}\n{example.source}Expected exception:\n"
f" {example.exc_msg}Got:\n {got}"
)
return f"{location}\n{example.source}{traceback.format_exc()}"
if example.exc_msg is not None:
return (
f"{location}\n{example.source}Expected exception:\n"
f" {example.exc_msg}Got: no exception"
)
if example.want and not checker.check_output(
example.want, stdout.getvalue(), flags
):
diff = checker.output_difference(example, stdout.getvalue(), flags)
return f"{location}\n{example.source}{diff}"
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The current implementation runs docstring examples in a shallow copy of the module's globals (namespace = dict(module_globals)). This prevents functions inside the module from seeing any global modifications or mocks made within the docstring, which is a common pattern in docstring examples. Additionally, the exception matching logic uses [-1] on the result of traceback.format_exception_only, which only captures the last line of the exception and will fail for multi-line exception messages.

To fix both issues, we should run the examples directly in the actual module_globals dictionary, and then restore its original state in a finally block. We should also use "".join(...) to capture the full exception message.

def run_docstring(
    docstring: DocstringExamples, module_globals: Dict, filename: str
) -> Optional[str]:
    """Run one docstring's examples in order. Return a report on failure."""
    checker = doctest.OutputChecker()
    original_globals = dict(module_globals)
    try:
        for example in docstring.examples:
            if example.options.get(doctest.SKIP):
                continue
            # example.lineno counts from the docstring's first line.
            line = docstring.lineno + example.lineno
            location = f"{filename}:{line} ({docstring.qualname})"
            flags = _optionflags(example)
            stdout = io.StringIO()
            try:
                # "single" mode echoes an expression's value, as the interactive
                # prompt the example imitates does.
                code = compile(example.source, location, "single")
                with contextlib.redirect_stdout(stdout):
                    exec(code, module_globals)
            except BaseException as e:  # noqa: BLE001 - report any failure.
                if example.exc_msg is not None:
                    got = "".join(traceback.format_exception_only(type(e), e))
                    if checker.check_output(example.exc_msg, got, flags):
                        continue
                    return (
                        f"{location}\n{example.source}Expected exception:\n"
                        f"    {example.exc_msg}Got:\n    {got}"
                    )
                return f"{location}\n{example.source}{traceback.format_exc()}"
            if example.exc_msg is not None:
                return (
                    f"{location}\n{example.source}Expected exception:\n"
                    f"    {example.exc_msg}Got: no exception"
                )
            if example.want and not checker.check_output(
                example.want, stdout.getvalue(), flags
            ):
                diff = checker.output_difference(example, stdout.getvalue(), flags)
                return f"{location}\n{example.source}{diff}"
    finally:
        for key in list(module_globals.keys()):
            if key not in original_globals:
                del module_globals[key]
            else:
                module_globals[key] = original_globals[key]
    return None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Half taken. Fixed in 9d7aafb: an expected exception is now compared against every line format_exception_only returns, joined, the way the standard library doctest runner does it. That means notes from add_note count, and a SyntaxError is trimmed to its message line. A new test fails on the old [-1] code. One correction: a multi-line message was already handled, because format_exception_only returns it as one element. The note lines after it were what got dropped.

Not changing the namespace. Stdlib doctest (DocTestFinder uses module.__dict__.copy()) and pytest doctest modules, which Ray's doctest targets use, both run each docstring in a copy of the module globals. Running in the real globals would make these results differ from the doctest targets. It would also let one docstring's names reach the next one.

Comment on lines +150 to +156
def module_name(path: str) -> str:
"""Map python/ray/data/aggregate.py to ray.data.aggregate."""
parts = path[len("python/") :] if path.startswith("python/") else path
parts = parts[: -len(".py")].split("/")
if parts[-1] == "__init__":
parts = parts[:-1]
return ".".join(parts)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The module_name function is fragile if the path contains leading ./ or redundant slashes, or if run on Windows where the path separator is \. We should normalize the path and use os.sep to make it cross-platform and robust.

Suggested change
def module_name(path: str) -> str:
"""Map python/ray/data/aggregate.py to ray.data.aggregate."""
parts = path[len("python/") :] if path.startswith("python/") else path
parts = parts[: -len(".py")].split("/")
if parts[-1] == "__init__":
parts = parts[:-1]
return ".".join(parts)
def module_name(path: str) -> str:
"""Map python/ray/data/aggregate.py to ray.data.aggregate."""
path = os.path.normpath(path)
if path.startswith("python" + os.sep):
path = path[len("python" + os.sep):]
parts = path[: -len(".py")].split(os.sep)
if parts[-1] == "__init__":
parts = parts[:-1]
return ".".join(parts)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changing this. Paths come from git diff --name-only or from the documented repo-relative arguments, so they always use / and have no ./ prefix. The step runs only on Linux CI images.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
Comment on lines +159 to +180
def changed_files(source_dir: str) -> List[str]:
base_branch = os.environ.get("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "master")
# Diff against FETCH_HEAD, as the docs example opt-in does: a clone with a
# restricted refspec may never create a local origin/<base>.
subprocess.check_call(["git", "fetch", "-q", "origin", base_branch])
output = subprocess.check_output(
[
"git",
"diff",
"--name-only",
"--diff-filter=M",
"FETCH_HEAD...HEAD",
"--",
source_dir.rstrip("/") + "/",
],
text=True,
)
return [
path
for path in output.split()
if path.endswith(".py") and not _EXCLUDED_DIRS.search(path)
]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The changed_files function currently hardcodes the remote name as origin and lacks support for a custom base ref. For developers working with forks, the main repository is often configured as upstream while origin points to their personal fork. If their fork's base branch is outdated, this will fetch from the wrong remote and compare against an incorrect base.

We should dynamically resolve the remote (checking for upstream first, then falling back to origin) and add support for an optional base parameter.

def changed_files(source_dir: str, base: Optional[str] = None) -> List[str]:
    if not base:
        base_branch = os.environ.get("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "master")
        remote = "origin"
        try:
            remotes = subprocess.check_output(["git", "remote"], text=True).split()
            if "upstream" in remotes:
                remote = "upstream"
        except Exception:
            pass
        subprocess.check_call(["git", "fetch", "-q", remote, base_branch])
        base = "FETCH_HEAD"

    output = subprocess.check_output(
        [
            "git",
            "diff",
            "--name-only",
            "--diff-filter=M",
            f"{base}...HEAD",
            "--",
            source_dir.rstrip("/") + "/",
        ],
        text=True,
    )
    return [
        path
        for path in output.split()
        if path.endswith(".py") and not _EXCLUDED_DIRS.search(path)
    ]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Half taken. Fixed in 9d7aafb: changed_files takes a base ref, and --base passes it through, so a clone where origin is a fork can run --source-dir python/ray/data --base upstream/master. Not adding remote detection. In CI, origin is always ray-project/ray. Locally, guessing between upstream and origin is a convention, not a guarantee, so the user names the ref.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
Comment on lines +190 to +207
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("files", nargs="*", help="Repo-relative .py files.")
parser.add_argument(
"--source-dir",
help="Without files, run the modified .py files under this directory.",
)
parser.add_argument(
"--list-changed",
action="store_true",
help="Print the modified files under --source-dir and exit.",
)
args = parser.parse_args()

files = args.files
if not files:
if not args.source_dir:
parser.error("pass files or --source-dir")
files = changed_files(args.source_dir)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Add a --base argument to the argument parser in main() and pass it to changed_files() to allow users to run the script locally against a specific base ref (e.g., upstream/master) without forcing a git fetch.

Suggested change
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("files", nargs="*", help="Repo-relative .py files.")
parser.add_argument(
"--source-dir",
help="Without files, run the modified .py files under this directory.",
)
parser.add_argument(
"--list-changed",
action="store_true",
help="Print the modified files under --source-dir and exit.",
)
args = parser.parse_args()
files = args.files
if not files:
if not args.source_dir:
parser.error("pass files or --source-dir")
files = changed_files(args.source_dir)
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("files", nargs="*", help="Repo-relative .py files.")
parser.add_argument(
"--source-dir",
help="Without files, run the modified .py files under this directory.",
)
parser.add_argument(
"--list-changed",
action="store_true",
help="Print the modified files under --source-dir and exit.",
)
parser.add_argument("--base", help="Diff HEAD against this ref.")
args = parser.parse_args()
files = args.files
if not files:
if not args.source_dir:
parser.error("pass files or --source-dir")
files = changed_files(args.source_dir, base=args.base)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9d7aafb, same change as the changed_files thread.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Outdated
failures = []
ran = skipped = 0
for path in files:
with open(path) as f:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Specify encoding="utf-8" when opening Python source files to prevent potential UnicodeDecodeError on systems where the default system encoding is not UTF-8 (e.g., Windows).

Suggested change
with open(path) as f:
with open(path, encoding="utf-8") as f:

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9d7aafb: source files open with encoding="utf-8".

Comment on lines +99 to +105
def _resolve_base() -> str:
base_branch = os.environ.get("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "master")
# Same fetch the docs example opt-in uses: a clone with a restricted
# refspec may never create a local origin/<base>.
subprocess.check_call(["git", "fetch", "-q", "origin", base_branch])
return _git("merge-base", "FETCH_HEAD", "HEAD").strip()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _resolve_base function hardcodes the remote name as origin. For developers working with forks, the main repository is often configured as upstream while origin points to their personal fork. If their fork's base branch is outdated, this will fetch from the wrong remote and compare against an incorrect base.

We should dynamically resolve the remote (checking for upstream first, then falling back to origin).

def _resolve_base() -> str:
    base_branch = os.environ.get("BUILDKITE_PULL_REQUEST_BASE_BRANCH", "master")
    remote = "origin"
    try:
        remotes = subprocess.check_output(["git", "remote"], text=True).split()
        if "upstream" in remotes:
            remote = "upstream"
    except Exception:
        pass
    # Same fetch the docs example opt-in uses: a clone with a restricted
    # refspec may never create a local origin/<base>.
    subprocess.check_call(["git", "fetch", "-q", remote, base_branch])
    return _git("merge-base", "FETCH_HEAD", "HEAD").strip()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changing this. check_docstring_only.py already takes --base, and ci.md shows the local run as --base "$(git merge-base upstream/master HEAD)". The fetch from origin runs only in CI, where origin is ray-project/ray.

@ray-gardener ray-gardener Bot added docs An issue or change related to documentation data Ray Data-related issues devprod labels Oct 8, 2026
@dstrodtman
dstrodtman force-pushed the doc-1754-docstring-only-label branch from 9d7aafb to e5ffb9d Compare October 13, 2026 13:14

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

Comment thread ci/ray_ci/doc/run_docstring_examples.py Resolved
Base automatically changed from doc-1704-docs-example-test-optin to master October 13, 2026 18:03
@dstrodtman
dstrodtman force-pushed the doc-1754-docstring-only-label branch from e5ffb9d to 2209674 Compare October 14, 2026 15:02
dstrodtman and others added 5 commits October 14, 2026 12:14
…ring-only

Replace the data: docstring doctests step, which ran the whole
//python/ray/data:doctest target, with data: docstring examples. It lists
the modules the PR modified, builds the Data CI image with the PR's Ray,
and runs ci/ray_ci/doc/run_docstring_examples.py on only those modules.
The runner extracts each docstring's >>> examples and runs them as plain
Python in the module's globals, failing on any exception.

Signed-off-by: Douglas Strodtman <[email protected]>
Where a >>> example shows output, the runner now compares what it prints,
using Ray's doctest matching (ELLIPSIS by default, plus per-example
directives), and checks expected exceptions. Examples that show no output
still only have to run.

Signed-off-by: Douglas Strodtman <[email protected]>
Compare an expected exception against every line format_exception_only
returns, so notes count, and trim a SyntaxError to its message line, as
the standard library's doctest runner does. Add --base so a local run in
a clone whose origin is a fork can diff against upstream/master, and read
source files as UTF-8.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1754-docstring-only-label branch from 2209674 to b4d92af Compare October 14, 2026 16:14

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b4d92af. Configure here.

Comment thread ci/ray_ci/doc/check_docstring_only.py Resolved
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Oct 14, 2026
The guard replaced a stripped docstring with `pass` on every owner,
including modules, so an empty file and a docstring-only file never
compared equal. Adding a package docstring to an empty `__init__.py`
failed the guard. Insert `pass` only for classes and functions, whose
bodies can't be empty.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman merged commit f4b0415 into master Oct 14, 2026
6 checks passed
@dstrodtman
dstrodtman deleted the doc-1754-docstring-only-label branch October 14, 2026 20:45
dstrodtman added a commit that referenced this pull request Oct 15, 2026
…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]>
dstrodtman added a commit that referenced this pull request Oct 15, 2026
#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>
dstrodtman added a commit that referenced this pull request Oct 20, 2026
…ithout torch or TensorFlow (#67083)

## Review guide

**For ray-ci reviewers.** About 660 lines need review. The other ~7,250
are the two generated lock files under `python/deplocks/docs/`.

1. **New image.** `docstringbuild` (`ci/docker/docstring.build.*`) is
built on `oss-ci-base_test` with a 138-package depset that has no torch,
TensorFlow, or cupy. Its layer is about 244 MB, against the 11.8 GB
`datalbuild-py3.10`.
1. **Routing.** In `.buildkite/test.rules.txt`, the new lock files and
requirements file run only `deplock_check`. The Dockerfile and wanda
spec run no steps, the same as `doctestbuild`.
1. **Step.** `doc: docstring examples` in `others.rayci.yml` replaces
`data: docstring examples` in `data.rayci.yml`.
1. **Cost to unlabeled PRs.** `python/ray` PRs gain one `docstringbuild`
image job, because rayci doesn't evaluate `if:`. Nothing else changes in
the generated pipelines.

**Result:** on premerge
[#74946](https://buildkite.com/ray-project/premerge/builds/74946), the
step drops from 10.1 to 4.2 min, and the cold image pull from 384 to 38
s.

**Approval:** ray-ci owns every file in this PR. `ray-core` was
requested only through the `/ci/` catch-all, which also lists ray-ci.

## Description

#66814 added the `docstring-only` label for Ray Data: under the label, a
PR runs the `>>>` examples in the modules it changed instead of Data's
test suites. This PR makes that examples step faster and extends it to
every library.

**Why.** The `data: docstring examples` step runs about 30 seconds of
examples, but takes about 10 minutes, because it runs in
`datalbuild-py3.10`. That image is built on the ML base image and is
about 11.8 GB compressed. On premerge
[#74929](https://buildkite.com/ray-project/premerge/builds/74929) and
[#74882](https://buildkite.com/ray-project/premerge/builds/74882),
pulling and extracting it took 384 and 386 seconds. The image chain also
delays the step's start: when wanda's cache misses,
`oss-ci-base_ml-py3.10` alone takes about 19 minutes.

**What this PR does:**

1. **A light depset.** `docstring_examples_depset_py3.10`, in
`docs.depsets.yaml`, is `ray[all]` plus the libraries the examples need:
    - dask.
- pytest. `ray.init()` starts the dashboard, which imports every module
under `ray/dashboard/modules` when it loads, including test modules in
packaged `tests/` directories, and nine of those import pytest. Without
it, the dashboard fails to start, and each `ray.init()` waits out a
30-second RPC deadline.
- The optional libraries that Ray Data's readers, writers, and
aggregations import lazily: pillow, pyiceberg, fastavro, soundfile,
decord, datasketches, and crc32c.

It has no torch, TensorFlow, or `cupy-cuda12x`. It expands
`ray_img_depset` with the same `requirements_compiled` constraints as
`doctest_depset` and `ci_data`, so every package resolves to the version
Ray's tests pin. It then relaxes `cupy-cuda12x` and `fastrlock`, which
only `ray[cgraph]` and cupy require. That leaves 138 packages, about 656
MB installed on Linux x86_64.
2. **A `docstringbuild` image.** It's built on `oss-ci-base_test` and
installs that lock. Locally its layer is about 244 MB compressed,
against roughly 0.9 GB for `oss-ci-base_test`. New `test.rules.txt`
entries route the image's files narrowly:
    - The lock files and requirements file run only `deplock_check`.
- The Dockerfile and wanda spec run no steps, as `doctestbuild`'s
already do.

Without these entries, the files fall to the general
`python/requirements/` and `ci/docker/` rules, which fan out across
every library and the release tests.
3. **Skip examples that need a library the image omits.**
`run_docstring_examples.py` reports a docstring as skipped, with the
library named, when it fails only because a library in
`OMITTED_LIBRARIES` isn't installed. That list covers torch, TensorFlow,
and a few others. Every docstring in a module that can't import without
one is skipped the same way.
- **Error shapes it recognizes:** a `ModuleNotFoundError`; an
`ImportError` chained to one, as in Ray Data's install-advice errors;
and a bare `ImportError` naming the library, such as RLlib's "PyTorch
was specified as the framework".
- **Safeguards:** the chain stops at `raise ... from None`, and an
installed library never matches, so nothing is skipped in a full image.
Any other import failure still fails the run.
- **No more aborted runs:** a module that fails to import is reported,
and the remaining modules still run.
- **Where skipped examples run instead:** their library's `doctest()`
target. That's in premerge for libraries whose suites the label doesn't
skip, and postmerge for Ray Data, because the label also turns off
`data: docs example tests`.
- **Where they're shown:** the step repeats them at the end of its log.
On a pass, they're in a `+++` section, which Buildkite opens expanded.
The step's container can't reach `buildkite-agent`, so it can't annotate
the build.
4. **One step for every library.** `doc: docstring examples` in
`others.rayci.yml` replaces `data: docstring examples`. It runs the
examples in every changed module under `python/ray` that a CPU
`doctest()` target covers, found with a `bazel query`, so it never runs
an example CI doesn't already run. Six files with runnable examples,
such as `util/iter.py` and `util/dask/scheduler.py`, have no `doctest()`
target and fail in any environment. The step names them and leaves them
out.

**Scope.** The examples step now covers every library. The label still
skips only Ray Data's test suites, through the existing per-step `if:`
gates. Skipping other libraries' suites the same way would mean a
negated `if:` on nearly every premerge test step. A better way is to let
rayci adjust tag selection from PR labels, a separate change to
`ray-project/rayci`. Until then, a labeled docstring-only PR outside
Data still runs its library's suites, so the new step adds coverage
there without saving time yet.

**Cost.** The step carries every library tag a `python/ray/` change can
emit, so a labeled PR selects it whatever it touches. rayci doesn't
evaluate `if:`, so an unlabeled Python PR that selects it still builds
`docstringbuild`, though Buildkite drops the step. I generated premerge
pipelines with rayci v0.48.0 against unmodified master. Unlabeled and
labeled Serve PRs and a labeled Data PR each gain exactly one image job,
`docstringbuild`, and nothing else changes. A doc-prose-only PR gains
nothing. The step also carries `oss`, like the label's scope guard.

## Related issues

Related to #66814.

## Additional information

**Not a duplicate.** #66814, which this extends, is merged. I searched
open PRs for the label, the step, and the image, and found nothing
overlapping.

**Tests run**

- `bazel test //ci/ray_ci/doc:test_run_docstring_examples`: 29 passed, 1
skipped (the existing Python 3.11+ `add_note` case). The new tests cover
each import-error shape, `raise ... from None`, both safeguards, the
coverage filter, and `main()` end to end.
- `bazel run //ci/raydepsets:raydepsets -- build
ci/raydepsets/configs/docs.depsets.yaml --check`: lock files are up to
date.
- `rayci test-rules` at v0.48.0: all 185 cases pass, including the new
ones. A deliberately wrong expectation fails, so the check is live.
- Pipeline generation with rayci v0.48.0 for the four PR shapes above,
compared against master.
- The image, built for linux/amd64 and linux/arm64 on a stand-in base,
because `oss-ci-base_test` is in CI's registry.
- `run_docstring_examples.py` over all 87 files with runnable examples
(323 docstrings) in the arm64 build, with the nightly wheel at the same
commit. Every file a CPU `doctest()` target covers either passes or
skips with the library named. The exception is `read_videos`, which
needs decord, and decord publishes no aarch64 wheel; the x86_64 image
installs it.
- `shellcheck` on `run_docstring_examples.sh`. The end of the script,
which preserves the exit status and repeats the skips, ran against a
stub `docker` for a passing run and a failing one.
- Locally, `ray.init()` with the dashboard's packaged test modules
present takes 31 s without pytest and 6 s with it, with the dashboard
up.

**Verified in CI.** This PR changes CI config, so the label's scope
guard would fail it. #67084, a test PR stacked on this one and not for
merge, edits a Data docstring and a Tune docstring under the label. Its
premerge,
[#74946](https://buildkite.com/ray-project/premerge/builds/74946),
passed:

- `docstringbuild` built on the real `oss-ci-base_test` in 138 s.
- The `docstring examples` step took 4.2 min, against 10.1 min on
`datalbuild-py3.10`.
- Pulling and extracting the image took 37.6 s on a cold agent, against
384 s.
- The step ran 53 docstrings across Data and Tune in 85 s: 0 failed, and
the 3 expected TensorFlow and torch examples skipped by name.

Details are in [this
comment](#67083 (comment)).
The first test run is what exposed the pytest gap above.

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]>
dstrodtman added a commit that referenced this pull request Oct 21, 2026
…#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]>
dstrodtman added a commit that referenced this pull request Oct 21, 2026
…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]>
dstrodtman added a commit that referenced this pull request Oct 29, 2026
…per-page doctest targets (#67204)

## Why are these changes needed?

Several contributor-facing CI docs fell behind the docs CI changes that
merged this month.

- **`ci.md`, "Docstring-only changes."** The section still described
`data: docstring examples` and said the examples step covers Ray Data
only. Since #67083, `doc: docstring examples` in `others.rayci.yml` runs
the changed modules' `>>>` examples for every library that a CPU
`doctest()` target covers. It runs in the light `docstringbuild` image,
which has no torch or TensorFlow, and reports examples that need those
libraries as skipped, by name. Since #67341, the label also skips every
library's test suites through `.buildkite/docs.labels.yaml`, so the
section now says that, and recommends an `@rtd-build` commit line
alongside the label so Read the Docs builds the API reference the
docstrings render into.
- **`ci.md`, broken steps and post-merge builds.** A new "Why some steps
show as broken" section says that on a PR the label rules remove the
steps a label skips, so they don't appear at all, that the scope guard
is the one label-gated step still shown as `broken` on an unlabeled PR,
and that scheduled post-merge builds don't apply label rules, so all
three label-gated steps show as `broken` there. The page also
distinguishes the two kinds of post-merge build on `master`. The build
each merge starts doesn't run the docs example tests, and the scheduled
builds that the release automation triggers run the full suite, so the
page now says "scheduled post-merge builds" wherever it means those.
- **`writing-code-snippets.md`, "How to test examples with GPUs."** It
told readers to open `doc/BUILD` and exclude their page from a
`glob(["source/**/*.rst"])` catch-all target. Neither exists: #66809 and
#67003 replaced library-wide prose targets with per-page
`doctest_each()` lists. The steps now show both cases: a doc page moves
from its library's `doctest_each` list to the GPU `doctest` rule, and a
docstring module moves from the CPU glob's `exclude` to the GPU rule. A
new short section says how a page with its first runnable example joins
CI, which the `doc_prose_doctest_targets` lint enforces.
- **`docs.md` and `writing-style.md`.** Both said CI enforces Vale. The
`documentation_style` check is out of the `lint.rayci.yml` matrix for
now, so they say the check is temporarily off.
- **`ci/ray_ci/doc/README.md`.** It described only the doc build and the
API guard. It now covers the scripts behind the `docs-example-test` and
`docstring-only` labels and `linkcheck_report.py`.
- **`doc/README.md`.** It said CI doesn't run linkcheck. The postmerge
`doc: linkcheck` step does, as a soft-fail step that never blocks.

Docs-only. No CI or behavior changes.

## Related issue number

None. Follows #66806, #66809, #66814, #67003, and #67083.

## Duplicate check

Not a duplicate. `gh pr list --repo ray-project/ray --state open`
searches for `"ci.md docstring"`, `"writing-code-snippets"`, and
`"ci/ray_ci/doc README"` return two other open PRs that touch these
files, both mine, neither covering these sections:

- #65868 adds a "How to test a Ray Serve deployment" section to
`writing-code-snippets.md` at the same insertion point as this PR's new
section, so whichever merges second needs a trivial rebase.
- #66884 updates the LLM doc paths in `ci.md`, not the docstring-only
section.

## Testing

- Every changed claim was checked against `master` at 3ae1b8b:
`.buildkite/others.rayci.yml`, `.buildkite/data.rayci.yml`,
`.buildkite/lint.rayci.yml`, `.buildkite/doc.rayci.yml`,
`doc/BUILD.bazel`, `python/ray/train/BUILD.bazel` (the GPU rule examples
are copied from the real `doctest[train-gpu]` and
`py_doctest[train-gpu]` rules), `doc/test_prose_doctest_targets.py`, and
the scripts under `ci/ray_ci/doc/`.
- `pre-commit run` on the changed files passes, including the
master-link check.
- Not run: a Sphinx build. The Read the Docs preview on this PR is the
check.

AI assistance (Claude Code) was used to find the stale text and draft
the changes. I reviewed every changed line.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
dstrodtman added a commit that referenced this pull request Nov 3, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data Ray Data-related issues devprod docs An issue or change related to documentation go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants