Skip to content

[tune] Correct Tune docstrings that contradict the code - #67611

Merged
pseudo-rnd-thoughts merged 2 commits into
masterfrom
doc-1922-tune-docstring-corrections
Oct 30, 2026
Merged

pseudo-rnd-thoughts merged 2 commits into
masterfrom
doc-1922-tune-docstring-corrections

Conversation

@dstrodtman

@dstrodtman dstrodtman commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Corrects eight Ray Tune docstrings that describe behavior the code doesn't have. This is a correctness change: it changes what the docstrings assert, so each item needs a technical read rather than a skim. The items surfaced while backfilling docstrings in #67608 and #67610.

Stacked on #67610, which is stacked on #67608. Several corrected lines sit right next to Args: blocks those PRs add, so a branch off master would conflict with both. This PR retargets to master once they merge.

Before and after

HyperBandForBOHB.choose_trial_to_run (schedulers/hb_bohb.py) opened with "Fair scheduling within iteration by completion percentage," copied from HyperBandScheduler. HyperBandScheduler sorts brackets by completion_percentage(), but the BOHB override iterates them in creation order and returns the first ready trial. The next sentence said the trial list from tune_controller isn't used, but the override reads tune_controller.get_trials() to check whether any trial is running. Both sentences now describe the override.

MedianStoppingRule.on_trial_result (schedulers/median_stopping_rule.py) said it compares a trial against "the running averages of all completed trials' objectives reported up to step t." The code compares against every other trial whose last result is at step t or later (_trials_beyond_time), whether or not it has completed, and each running average covers results from grace_period to t (_running_mean).

tune.quniform (search/sample.py) gave tune.uniform(1, 10) as its example. It now uses tune.quniform(1, 10, 0.5) and says the value is rounded to a multiple of 0.5, which is what Quantized.sample does.

tune.randint (search/sample.py) gave tune.randint(10) as its example, but upper has no default, so that call raises a TypeError. It now uses tune.randint(0, 10).

Stopper (stopper/stopper.py) said "By default, this class does not stop any trials." The base __call__ and stop_all raise NotImplementedError. The docstring now says so.

ExperimentPlateauStopper (stopper/experiment_plateau.py) listed a ValueError when patience isn't "a strictly positive integer." The check is patience < 0, and patience defaults to 0. The Raises: entry now says "a non-negative integer." The runtime error message says "strictly positive" too, but it's a code string, so it changes in #67612.

BasicVariantGenerator.restore_from_dir (search/basic_variant.py) said it "Restores self + searcher + search wrappers," copied from SearchGenerator. BasicVariantGenerator has no searcher or wrappers. It loads the newest checkpoint and calls set_state, and the summary now says that.

tune.run and RunConfig, verbose (tune/tune.py and air/config.py) said that setting RAY_AIR_NEW_OUTPUT=1 switches to the old verbosity levels. It's the reverse. get_air_verbosity in tune/experimental/output.py falls back to the old output only when the variable is "0", and it defaults to "1". Both docstrings now say RAY_AIR_NEW_OUTPUT=0.

Behavior is unchanged. The diff touches only docstrings, which the guard below confirms.

For reviewers

If HyperBandForBOHB is meant to schedule by completion percentage like its parent, the bug is in the code rather than the docstring. Say so and I'll drop that item in favor of a code fix. The override's comments mark it as BOHB-specific ("MAIN CHANGE HERE"), but none of them explain the ordering.

air/config.py is owned by @ray-project/ray-train. It carries the same RAY_AIR_NEW_OUTPUT sentence as tune.py, so both get the same fix here.

Duplicate check

No open PR edits these docstrings. Open PRs #66710 and #67137 change code in hyperband.py, and #66923 changes CombinedStopper code in stopper.py. None of them touch the lines changed here.

Testing

  • python ci/ray_ci/doc/check_docstring_only.py --base doc-1922-tune-api-docstrings: docstring-only guard: 8 file(s), docstrings only.
  • The full pre-commit suite on the changed files, including ruff, black, pydoclint, and the docstyle hook: passed.
  • The commit carries an @rtd-build line, so the Read the Docs preview renders the changed docstrings.

AI assistance (Claude Code) was used to prepare this PR.

🤖 Generated with Claude Code

@dstrodtman dstrodtman added tune Tune-related issues go add ONLY when ready to merge, run all tests docstring-only Skip heavy library tests for Ray API docstring edits. labels Oct 30, 2026
@dstrodtman
dstrodtman requested review from a team as code owners October 30, 2026 15:21

@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 focuses on improving and correcting documentation across Ray Air and Ray Tune. Key updates include correcting the environment variable reference for legacy verbosity settings to RAY_AIR_NEW_OUTPUT=0, clarifying trial selection logic in BOHB, explaining the median stopping rule calculations, correcting sampling function examples for quniform and randint, and updating stopper documentation. There are no review comments, so I have no feedback to provide.

@dstrodtman
dstrodtman force-pushed the doc-1922-tune-docstring-corrections branch from da140d0 to b8093e6 Compare October 30, 2026 15:23
@dstrodtman
dstrodtman force-pushed the doc-1922-tune-docstring-corrections branch from b8093e6 to a7ece3f Compare October 30, 2026 16:21
Base automatically changed from doc-1922-tune-api-docstrings to master October 30, 2026 16:39
dstrodtman and others added 2 commits October 30, 2026 12:39
Fix eight docstring claims that the code doesn't match:

- HyperBandForBOHB.choose_trial_to_run returns the first ready trial in
  bracket creation order. It doesn't sort by completion percentage, and
  it does read tune_controller.
- MedianStoppingRule.on_trial_result compares against every other trial
  that has reached the current step, not only completed ones, averaged
  from grace_period onward.
- The quniform example called tune.uniform, and the randint example
  called tune.randint(10), which has no default upper bound.
- Stopper's base methods raise NotImplementedError. They don't default
  to never stopping.
- ExperimentPlateauStopper accepts patience=0, its default.
- BasicVariantGenerator.restore_from_dir restores only the generator.
  It has no searcher or wrappers.
- RAY_AIR_NEW_OUTPUT=0, not 1, selects the legacy verbosity levels, in
  both tune.run and RunConfig.

Docstring-only: no code changes.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
Define t as the result's time_attr value before using it, then state
the comparison in order: which trials take part, what window their
averages cover, and when the rule stops the trial. The claims are
unchanged from the previous commit.

Docstring-only: no code changes.

@rtd-build

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman force-pushed the doc-1922-tune-docstring-corrections branch from 060966f to c7642ab Compare October 30, 2026 16:39
@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit ec065ce into master Oct 30, 2026
6 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1922-tune-docstring-corrections branch October 30, 2026 17:01
dstrodtman added a commit that referenced this pull request Oct 30, 2026
…umented (#67612)

## Summary

Adds type hints to four public Ray Tune methods so their parameters can
be documented, and documents them: `BasicVariantGenerator.set_state` and
`save_to_dir`, `FunctionStopper.is_valid_function`, and
`Trainable.reset`. It also corrects the `ExperimentPlateauStopper` error
message for `patience`.

Stacked on #67610, which writes the docstrings these `Args:` sections
extend. It retargets to `master` once #67610 and #67608 merge.

## Why this isn't in the docstring-only PRs

Ray's pydoclint hook runs with `--arg-type-hints-in-signature`, so it
rejects an `Args:` section on a signature without type hints. These four
methods had none, so documenting their 6 parameters needs a signature
change. A signature change isn't docstring-only, so it's in its own PR
without the `docstring-only` label, and premerge runs Tune's tests on
it.

## Changes

- `BasicVariantGenerator.set_state(self, state: Dict)`, with `Args:`.
- `BasicVariantGenerator.save_to_dir(self, dirpath: str, session_str:
str) -> Optional[bool]`, with a docstring, `Args:`, and `Returns:`. It
returns `False` when it skips saving because variants are generated
lazily, and otherwise `None`.
- `FunctionStopper.is_valid_function(cls, fn: Any) -> bool`, with
`Args:`, `Returns:`, and `Raises:`.
- `Trainable.reset(self, new_config: Dict, storage:
Optional[StorageContext] = None) -> bool`, with `Args:` and `Returns:`.
- `ExperimentPlateauStopper` raised `"Patience must be a strictly
positive integer."`, but the check is `patience < 0` and `patience`
defaults to `0`. The message now says "a non-negative integer." The
matching `Raises:` entry is corrected in #67611.

The type hints don't change behavior. Every name they use is already
imported at runtime in its module.

## Duplicate check

No open PR changes these signatures. #67013 changes `Repeater` in
`search/repeater.py`, which this PR doesn't touch. This branch merges
cleanly with #67611, its sibling on #67610.

## Testing

- The full pre-commit suite on the changed files, including ruff, black,
pydoclint, and the docstyle hook: passed.
- No test asserts the old `patience` error message (`grep -rn "Patience
must" python/ray`).
- Tune's unit tests run in premerge on this PR.

AI assistance (Claude Code) was used to prepare 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 Nov 3, 2026
## Description

This PR changes what three Tune docstring examples check, and corrects
defects that converting them exposed. It needs review from Tune
maintainers. It isn't a syntax-only conversion.

The `Callback`, `ResultGrid`, and `ResultGrid.get_dataframe` examples
were `.. testcode::` blocks, which griffe and MkDocs don't render. Each
was paired with a hidden `testoutput` whose body was only `...`, which
matches any output, so the doctest ran the code but checked nothing it
printed. This PR converts them to `>>>` doctests that show their output,
and makes these corrections:

**`ResultGrid` class example**

- **Removes the `try`/`except ValueError` around `tuner.fit()`.** It
never fires. A trial that raises is recorded in the result grid and
doesn't propagate out of `fit()`, as the "Failure handling" paragraph of
`Tuner.fit`'s docstring says. In a run of this example, `fit()` returned
normally with 5 of 10 trials errored. If `fit()` had raised, the loop
that follows would have failed with a `NameError` on `result_grid`.
- **Adds the missing space in the success message.** The two f-strings
concatenated to `with metrics{'loss': 0.0, ...}`.
- **Passes `filter_metric` and `filter_mode` to `get_dataframe`.** The
example passed `metric=` and `mode=`, which `get_dataframe` doesn't
accept. The line is `+SKIP`, so nothing caught the `TypeError`.
- Normalizes the over-indented `print` calls in the loop to four spaces.

**`Callback` class docstring**

- **Replaces the two `TrialRunner` references.** Tune no longer has a
`TrialRunner` class. Callbacks are passed through
`RunConfig(callbacks=...)`, as the example itself does, and
`TuneController` calls them
(`python/ray/tune/execution/tune_controller.py`).
- The example now shows its `Got result: 0` through `Got result: 9`
lines.

**`Tuner.fit` docstring**

- **Corrects the `Raises` section.** It said `fit()` raises
`RayTaskError` whenever the trainable raises, which contradicts the same
docstring's "Failure handling" paragraph.
`TuneController._trial_task_failure` re-raises a trial's exception only
when `fail_fast` is `"raise"`, and otherwise logs it and records it on
the trial. I ran a trainable that raises `ValueError` under each
`FailureConfig(fail_fast=...)` setting. With `False` and `True`, `fit()`
returned a `ResultGrid` with `num_errors == 1`. With `"raise"`, it
raised `RayTaskError(ValueError)`, which is also a `ValueError`. That's
probably where the `ResultGrid` example's `except ValueError` came from.

**How the output is matched.** Tune prints its progress tables to
stdout, which a stock doctest compares. The examples use the pattern
`python/ray/tune/stopper/stopper.py` already uses: `print("[ignore]");
result_grid = tuner.fit() # doctest: +ELLIPSIS`, with `[ignore]...` as
the expected output. In the `Callback` example, the expected output is
`[ignore]...`, then `Got result: 0`, `...`, `Got result: 9`, and `...`,
so the callback's own lines are still checked. The `ResultGrid`
example's trainable fails at random, so its loop's expected output is
`Trial ...`.

**For reviewers**

- Is the `[ignore]` pattern acceptable in rendered API reference, or
would you prefer `RunConfig(verbose=0)` in these examples? That changes
the example code, so I didn't make it here.
- The `ResultGrid` example fails half its trials at random, so its
printed output can't be pinned down. It could fail trials based on the
config instead, so the output is deterministic. I kept the example's
behavior.

## Related issues

Related to #66748, which converted `Callback`'s method examples and left
this class example, and to #67619, the syntax-only conversion of Tune's
remaining never-run examples.

## Additional information

**Not a duplicate.** I searched open PRs for Tune doctest and `testcode`
changes. None touches these docstrings. #67611, which has merged,
corrected other Tune docstrings.

**Tests run**

These ran in a Python 3.12 virtualenv with `ray[tune]==2.59.0`, with
this branch's `callback.py` and `result_grid.py` copied over the
installed ones. The installed files differ from `master` only in
docstrings.

- `pytest --doctest-modules -p default_doctest_pytest_plugin` on both
files, using `bazel/default_doctest_pytest_plugin.py`, the way
`//python/ray/tune:py_doctest[tune]` runs them: 4 passed and 1 skipped,
three runs in a row. The skip is `get_best_result`'s existing `+SKIP`
example.
- To confirm the `Callback` example checks the callback's output, I
changed the expected `Got result: 9` to `Got result: 99`. The doctest
failed.
- `ci/ray_ci/doc/check_docstring_only.py --base upstream/master`: "3
file(s), docstrings only."
- `pre-commit run --files` on all three files: all hooks pass.

The PR carries the `docstring-only` label, and its commit carries an
`@rtd-build` line for the Read the Docs preview.

AI assistance (Claude Code) was used for this PR.

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

---------

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docstring-only Skip heavy library tests for Ray API docstring edits. go add ONLY when ready to merge, run all tests tune Tune-related issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants