Skip to content

fix(tune): release per-trial logger state on trial end to bound driver memory - #66699

Open
SIDDARTHAREDDY8 wants to merge 1 commit into
ray-project:masterfrom
SIDDARTHAREDDY8:sprint20-build-17
Open

SIDDARTHAREDDY8 wants to merge 1 commit into
ray-project:masterfrom
SIDDARTHAREDDY8:sprint20-build-17

Conversation

@SIDDARTHAREDDY8

Copy link
Copy Markdown

Fixes #64231

Problem: The default Tune auto loggers pin every finished trial: JsonLoggerCallback._trial_configs and CSVLoggerCallback._trial_continue are dicts keyed by Trial objects that are never released, so driver RSS grows linearly with completed trials (confirmed via tracemalloc + gc profiling).

Fix: Release per-trial state on trial end — both dicts are popped in log_trial_end (including the early-return path where no result file was opened). TrialProgressCallback gains _discard_trial_state(), called from on_trial_error and on_trial_complete, clearing _completed_trials, _last_print, _last_print_iteration, _last_result_str, and _last_result. TBX/Aim loggers already cleaned up; TuneController's retained finished trials are by design (ResultGrid/ExperimentAnalysis) and out of scope.

Tests: new unit tests with weakref pinning checks proving trial objects are collectable after log_trial_end, plus a mechanism-level repro driving the real default callback stack through 3000 trial lifecycles showing flat memory.

@SIDDARTHAREDDY8
SIDDARTHAREDDY8 requested a review from a team as a code owner October 4, 2026 03:36

@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 addresses a memory leak issue where finished trials are retained in memory by the default loggers and progress callbacks, leading to linear RSS growth. It ensures that trial states, config snapshots, and continue flags are properly discarded upon trial completion or error. Additionally, regression tests are introduced to verify proper cleanup. The reviewer suggests improving the test assertions by checking against an empty list of alive references instead of using assertTrue(all(...)), which will provide much more descriptive error messages on failure by identifying the leaked Trial objects.

Comment thread python/ray/tune/tests/test_logger.py Outdated
# cleanup the trials must be collectable.
del trial
gc.collect()
self.assertTrue(all(ref() is None for ref in refs))

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

Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.

self.assertEqual([ref() for ref in refs if ref() is not None], [])

Comment thread python/ray/tune/tests/test_logger.py Outdated
self.assertEqual(len(logger._trial_csv), 0)
del trial
gc.collect()
self.assertTrue(all(ref() is None for ref in refs))

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

Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.

self.assertEqual([ref() for ref in refs if ref() is not None], [])

Comment thread python/ray/tune/tests/test_logger.py Outdated
self.assertEqual(len(bookkeeping), 0)
del trial
gc.collect()
self.assertTrue(all(ref() is None for ref in refs))

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

Using self.assertTrue(all(ref() is None for ref in refs)) will only show False is not True on failure, which doesn't help identify which Trial objects were leaked. Asserting against an empty list of alive references provides a much more descriptive error message showing the leaked objects.

self.assertEqual([ref() for ref in refs if ref() is not None], [])

@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

Reviewed by Cursor Bugbot for commit 8d33c0f. Configure here.

Comment thread python/ray/tune/progress_reporter.py Resolved
@SIDDARTHAREDDY8
SIDDARTHAREDDY8 force-pushed the sprint20-build-17 branch 2 times, most recently from c3f39e6 to 30819c1 Compare October 4, 2026 03:58
…ni-code-assist review)

Signed-off-by: SIDDARTHA REDDY <[email protected]>
@SIDDARTHAREDDY8

Copy link
Copy Markdown
Author

Addressed the gemini-code-assist review nit: the three regression tests now assert assertEqual([ref() for ref in refs if ref() is not None], []) instead of assertTrue(all(...)), so a failure names the leaked Trial objects. No behavior change. (The separate cursor review point about _discard_trial_state popping _last_result is still awaiting the author's call.)

@ray-gardener ray-gardener Bot added tune Tune-related issues community-contribution Contributed by the community labels Oct 4, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 18, 2026
@SIDDARTHAREDDY8

Copy link
Copy Markdown
Author

Still active on this one, the stale flag is just inactivity on my side. The cursor[bot] feedback above is addressed in the current head: _discard_trial_state now re-keys the finished trial's _last_result entry by str(trial) instead of dropping it, so finished trials stay visible in the notebook progress table while the Trial objects themselves become collectable. Regression tests cover both halves (all table rows still render, all Trial weakrefs clear). Happy to adjust the approach if a maintainer prefers something else, ready for review whenever.

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 19, 2026
@SIDDARTHAREDDY8

Copy link
Copy Markdown
Author

Just checking whether there is anything you would like adjusted here — happy to revise.

dstrodtman added a commit that referenced this pull request Oct 30, 2026
…67610)

## Summary

Adds the missing docstrings, `Args:` entries, and `Returns:` sections on
public Ray Tune symbols in `search`, `stopper`, `trainable`, `context`,
`utils`, `execution`, and `logger`. Each describes existing behavior,
written from the code. It follows #67608, which covers
`ray.tune.schedulers`.

Stacked on #67608: this PR targets that branch so the correctness PR
above it can build on both, and retargets to `master` once #67608
merges. The two PRs share no files.

## Before

Across these subpackages, 23 public symbols had no docstring, 43
parameters had no `Args:` entry, and 14 callables that annotate a return
type had no `Returns:` section. The sampling functions such as
`tune.uniform`, `tune.quniform`, and `tune.randint` described their
bounds in prose but had no `Args:` block.

## After

19 of the 23 docstrings, 35 of the 43 parameters, and 10 of the 14
`Returns:` sections are documented. Where a base class lacked the
docstring its overrides inherit, this PR documents the base instead of
each override: `Searcher.get_state`, `Searcher.set_state`,
`Stopper.__call__`, and `Stopper.stop_all`. That covers both
`ConcurrencyLimiter` classes and `Repeater`, and `CombinedStopper`.

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

## Not in this PR

- **Four methods with untyped signatures:**
`BasicVariantGenerator.set_state` and `save_to_dir`,
`FunctionStopper.is_valid_function`, and `Trainable.reset`. pydoclint,
run with `--arg-type-hints-in-signature`, rejects an `Args:` section on
a signature without type hints, so documenting these 6 parameters needs
a signature change. That signature change is in #67612, since this PR is
docstring-only. `BasicVariantGenerator.set_state` and
`FunctionStopper.is_valid_function` get a docstring here, without
sections.
- **`TuneContext.get_trial_name`, `get_trial_id`, `get_trial_resources`,
and `get_trial_dir`:** these take their docstrings at runtime from
`ray.train._internal.session` through `@_copy_doc`, so they render
documented already. A docstring written on the method would be
overwritten. Their `Returns:` sections belong on the `session`
functions, which Ray Train owns.
- **`Repeater.on_trial_complete`:** #67013 changes this method and edits
the same docstring, so its `Args:` entries are left to land after that
PR.

## For reviewers

These docstrings are worth a close read:

- `Verbosity` documents the four levels as the `verbose` argument of
`tune.run` describes the legacy output, and notes that the default
output treats levels 2 and 3 the same (`get_air_verbosity` in
`tune/experimental/output.py`).
- `PlacementGroupFactory.__call__` is deprecated. Its new docstring says
so and points to `to_placement_group()`.
- `BasicVariantGenerator.get_state` documents that it returns `False`
instead of a state when any variants are generated lazily.

## Duplicate check

No open PR documents these symbols. Open PRs #66923 (`stopper.py`),
#66699 (`logger/json.py`), and #58359 (`utils/util.py`) change code in
files this PR touches, and all three apply cleanly on top of this
branch. #67013 (`repeater.py`) also applies cleanly, because this PR
leaves the method it changes alone.

## Testing

- `python ci/ray_ci/doc/check_docstring_only.py --base "$(git merge-base
upstream/master HEAD)"`: `docstring-only guard: 15 file(s), docstrings
only.`
- The full pre-commit suite on the changed files, including ruff, black,
pydoclint, and the docstyle hook: passed.
- `ci/ray_ci/doc/api_param_coverage.py`, run over `python/ray/tune/`
outside `schedulers/`: 43 undocumented parameters on `master`, 8 on this
branch: 6 on the four untyped signatures and 2 on
`Repeater.on_trial_complete`, all listed above.
- 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](https://claude.com/claude-code)

Signed-off-by: Douglas Strodtman <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community tune Tune-related issues unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Tune] Ray Tune memory leak: RSS grows linearly with trial count in tune.run()

1 participant