Skip to content

[rllib] Fix MultiAgentEpisode.get_truncateds returning the terminated flag for "__all__" - #67627

Merged
pseudo-rnd-thoughts merged 5 commits into
masterfrom
doc-1914-rllib-get-truncateds-fix
Nov 6, 2026
Merged

pseudo-rnd-thoughts merged 5 commits into
masterfrom
doc-1914-rllib-get-truncateds-fix

Conversation

@dstrodtman

Copy link
Copy Markdown
Contributor

Why are these changes needed?

MultiAgentEpisode.get_truncateds() builds its "__all__" entry from self.is_terminated instead of self.is_truncated:

truncateds.update({"__all__": self.is_terminated})

So an episode that's terminated but not truncated reports get_truncateds()["__all__"] == True. get_terminateds(), two methods up, reads self.is_terminated as expected, and this looks like a copy of it that missed one name.

This PR:

  • Reads self.is_truncated for "__all__" in get_truncateds().
  • Adds a docstring with a Returns: section, matching the one on get_terminateds(). The method had none.
  • Adds test_get_terminateds_and_truncateds to test_multi_agent_episode.py.

The only caller in RLlib is MultiAgentEpisode.cut(), which passes get_truncateds() to the successor episode's constructor. With the old code, cutting a terminated episode produced a successor with is_truncated=True.

A related question for RLlib, not changed here

When every agent is done after an add_env_step() call, the "Case 2" block in add_env_step() sets self.is_terminated = True even if all agents were truncated rather than terminated. A fully truncated episode therefore reports both is_terminated and is_truncated as True. The comment above the block describes a mix of truncated and terminated agents, so this might be intended or might be broader than intended. This PR leaves it alone, and the new test doesn't assert get_terminateds() for the truncated case because of it.

Related issue number

None. I found this while adding docstrings to ray.rllib.env in #67626, which leaves get_truncateds out so that its docstring doesn't describe the bug. I searched open PRs for get_truncateds and multi_agent_episode and found no overlap.

Checks

  • pytest --noconftest python/ray/rllib/env/tests/test_multi_agent_episode.py against the branch's rllib on top of the current nightly wheel: 19 passed.
  • The same new test against the original line: fails, as expected.
  • pre-commit run --files <changed files>: all hooks pass.

AI assistance (Claude Code) was used to find the bug and draft the fix and test. I reviewed every changed line.

🤖 Generated with Claude Code

… flag for "__all__"

get_truncateds set its "__all__" entry from self.is_terminated instead of
self.is_truncated, so a terminated, untruncated episode reported itself as
truncated. Read is_truncated, add a docstring, and add a test covering both
flags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Douglas Strodtman <[email protected]>
@dstrodtman
dstrodtman requested a review from a team as a code owner October 30, 2026 17:45
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@ray-gardener ray-gardener Bot added rllib RLlib related issues docs An issue or change related to documentation labels Oct 30, 2026
@dstrodtman dstrodtman added the go add ONLY when ready to merge, run all tests label Nov 3, 2026
pseudo-rnd-thoughts pushed a commit that referenced this pull request Nov 3, 2026
## Why are these changes needed?

The public env wrappers in `ray.rllib.env.wrappers` (`atari_wrappers`,
`dm_control_wrapper`, `dm_env_wrapper`, and `pettingzoo_env`) mostly
have no class docstrings and few method docstrings, so `help()` and IDE
tooltips show little for them. This PR documents their existing
behavior, and fixes one crash in `dm_env_wrapper.py` that's described
below.

It also adds parameter type hints. Ray runs pydoclint with
`--arg-type-hints-in-signature`, so a docstring with an `Args:` section
fails the check unless every parameter has a hint. Because of that this
can't be a `docstring-only` PR. Apart from the fix below, it doesn't
change runtime behavior. Stripping docstrings, annotations, and imports,
the AST of every changed file matches `master`, except for that fix in
`dm_env_wrapper.py`.

### Fix: `DMEnv` space conversion

`dm_env_wrapper._convert_spec_to_space` called `np.asscalar`, which
NumPy removed in 1.23, so converting any `BoundedArray` spec raised
`AttributeError`. That included a `Dict` spec that contains one. The fix
passes `np.broadcast_to(spec.minimum, spec.shape)` and the same for
`maximum` as the `Box` bounds. Broadcasting is needed because `dm_env`
stores scalar bounds as 0-d arrays, which `Box` rejects against a
non-empty shape. It also handles array-valued bounds, which
`np.asscalar` rejected even before its removal.

What changed:

- **`atari_wrappers.py`:** Class docstrings with `Args:` for every
wrapper, folding in the text that sat in `__init__` docstrings.
Docstrings, `Args:`, and `Returns:` on each `step`, `reset`,
`observation`, and `reward` override, on `MonitorEnv`'s stats getters,
and on `get_wrapper_by_cls`. Type hints use gymnasium's `ActType` and
`ObsType`.
- **`dm_control_wrapper.py`:** A class docstring for `DMCEnv` covering
all 12 constructor arguments, plus docstrings for its spaces, `step`,
`reset`, and `render`.
- **`dm_env_wrapper.py`:** `Args:` on the `DMEnv` class docstring, plus
docstrings for `step`, `reset`, and its spaces and `reward_range`.
- **`pettingzoo_env.py`:** `Args:` on `PettingZooEnv`, a class docstring
for `ParallelPettingZooEnv`, and docstrings for `PettingZooEnv.step`,
`close`, and `get_sub_environments`.

None of these wrappers has a page on docs.ray.io, so the docstrings show
up in `help()` and in IDEs.

### Issues found, not changed here

These look like bugs too, but the right fix depends on intent, so I left
them alone:

- `DMEnv.render()` always raises `ValueError("Environment not
started...")`, because nothing ever sets `self._prev_obs`. I didn't add
a docstring that describes a return value it can't produce.
- `DMEnv.reset()` and `DMCEnv.reset()` ignore `seed` and `options`. The
new docstrings say so.

For `render()`, a `dm_env` observation is often a dict of state arrays
rather than an RGB frame, so whether it should return the observation,
read from physics, or go away is the owners' call.

## Related issue number

None. This continues #67626, which documents the rest of
`ray.rllib.env`, and is separate from #67627, which fixes
`MultiAgentEpisode.get_truncateds`. I searched open PRs for these files
and for RLlib docstring work and found no overlap.

## Checks

- `pre-commit run --files <changed files>`: all hooks pass, including
pydoclint 0.9.1 with the repo's arguments.
- AST comparison against `upstream/master` with docstrings, annotations,
and imports stripped: identical for all four files.
- `pytest python/ray/rllib/env/tests/test_pettingzoo_env.py` against
this branch's `rllib` on the current nightly wheel, with the test
requirements' `pettingzoo==1.24.3` and `supersuit==3.9.3`: 2 passed.
- `_convert_spec_to_space` with `dm-env` installed, on a `BoundedArray`
with scalar bounds, one with array bounds, a `DiscreteArray`, an
unbounded `Array`, and a `Dict` of specs: all five convert. The original
code raises `AttributeError` on three of them.
- All four modules import cleanly. A smoke test on a fake image env
checked `FrameStack`, `GrayScaleAndResize`, `NormalizedImageEnv`,
`ClipRewardEnv`, `MaxAndSkipEnv`, `MonitorEnv`, and `get_wrapper_by_cls`
against the shapes and values the new docstrings state. The
Atari-specific wrappers need ROMs and weren't run.

AI assistance (Claude Code) was used to draft the docstrings, type
hints, and fix. 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]>
@dstrodtman dstrodtman added the skip-gpu-tests Skips GPU tests for PRs that trigger them due to overly broad rules. label Nov 3, 2026

@pseudo-rnd-thoughts pseudo-rnd-thoughts left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Well this would have caused significant issues @ArturNiederfahrenhorst

pseudo-rnd-thoughts added a commit that referenced this pull request Nov 5, 2026
…67863)

## Why are these changes needed?

When every agent is done after `MultiAgentEpisode.add_env_step()`, the
"Case 2" block sets `self.is_terminated = True` regardless of *why* the
agents are done. A fully truncated episode (the common time-limit case,
`truncateds={"__all__": True}`) is therefore reported as **both**
terminated and truncated:

```python
e = MultiAgentEpisode(observations=[{"a": 0, "b": 0}])
e.add_env_step(..., terminateds={"__all__": False},
               truncateds={"a": True, "b": True, "__all__": True})
e.is_terminated, e.is_truncated  # (True, True) on master
```

Because `add_env_step()` sets each agent's flag as
`terminateds.get(agent_id) or self.is_terminated`, the wrong flag also
reaches every agent's `SingleAgentEpisode`. Training code that reads it
then treats time-limit truncations as true terminal states and does not
bootstrap the value of the last observation:

- `AddOneTsToEpisodesAndTruncate` (PPO/GAE value targets) reads
`sa_episode.is_terminated`.
- `MultiAgentEpisodeReplayBuffer` reads `ma_episode.is_terminated`
before the truncated flag, so the last transition of every agent gets
`TERMINATEDS=True, TRUNCATEDS=False`.

This change makes Case 2 declare the episode terminated only if at least
one agent terminated (at this or a prior timestep), and truncated if all
agents were only truncated. Episodes that mix terminated and truncated
agents still count as terminated, as the existing comment describes, and
the `__all__` handling (Case 1) is unchanged.

This was flagged in #67627, which fixes `get_truncateds()["__all__"]`
but leaves this block alone. With both PRs merged, `get_terminateds()`
and `get_truncateds()` are correct for fully truncated episodes.

## Not a duplicate

- #67627 fixes only `get_truncateds()` returning `is_terminated` for
`"__all__"`. It points out this bug but doesn't change it.
- #66913 changes *which* agents the Case 2 check considers (agents
joining in the same step). It doesn't change *what* Case 2 decides. The
two PRs edit the same lines, so whichever merges second needs a small
rebase.
- No open issue covers this.

## Known limitation (out of scope)

In the mixed case (one agent terminated and another truncated at the
same step, without `__all__`), the episode is terminated and that flag
is still propagated to the truncated agent's `SingleAgentEpisode`.
That's existing behavior, and changing the propagation could interact
with #66913's newcomer handling, so I left it for a follow-up.

## Testing

Added `test_add_env_step_all_agents_done_terminated_vs_truncated`. It
covers: all agents truncated with and without `__all__`; agents
truncated at different timesteps; mixed terminated/truncated at the same
step and across steps; and all agents terminated. It fails on master
(`AssertionError: True is not false`) and passes with this change.

`ray.init()` in the test class's `setUpClass` hangs on my local macOS
machine, so I ran the `TestMultiAgentEpisode` cases through `unittest`
with `ray.init` stubbed out (the episode tests don't use Ray; I excluded
the env-runner test):

```
TestMultiAgentEpisode (18 tests): Ran 18 tests ... OK
pytest python/ray/rllib/utils/replay_buffers/tests/test_multi_agent_episode_buffer.py \
       python/ray/rllib/utils/replay_buffers/tests/test_multi_agent_prio_episode_buffer.py
7 passed
pre-commit run --files <changed files>: passed
```

CI runs the full test file, including the env-runner test.

## AI assistance

AI assistance (Claude Code) was used to find the issue, write the fix
and the test, and draft this description.

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

Signed-off-by: Mark Towers <[email protected]>
Co-authored-by: Mark Towers <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
dstrodtman added a commit that referenced this pull request Nov 5, 2026
…67834)

## Description

`//python/ray/rllib:doctest` fails on master in the `APPOConfig` and
`IMPALAConfig` examples. #67774 made these examples runnable. Each one
builds an algorithm with `learners(num_learners=1)`, and the learner
worker sets up a Gloo process group and prints this line:

```
(_WrappedExecutable pid=5360) [Gloo] Rank 0 is connected to 0 peer ranks. Expected number of connected peer ranks is : 0
```

Ray forwards worker output to the driver's stdout asynchronously. Stock
doctest compares the driver's stdout against each example's expected
output, so the line fails `algo = config.build()`, which expects
nothing. Both bazel attempts failed this way in [premerge build
76224](https://buildkite.com/ray-project/premerge/builds/76224) on
#67627, which doesn't touch these files. Any RLlib PR that runs the full
doctest target without the `docstring-only` label hits the same failure.
#67774 passed premerge because it ran with `docstring-only`, which runs
docstring examples in a light image without torch and skips these
examples by name.

This PR sets `RAY_LOG_TO_DRIVER=0` in the target's `env`. `ray.init()`
reads that constant when it isn't passed `log_to_driver`, and these
examples don't pass it. #67831 sets the same variable on the Train V2
doctest target for the same Gloo output from `TorchTrainer` workers. No
RLlib docstring example expects worker output: a search of
`python/ray/rllib` outside `examples/` and `tests/` for `pid=` and
worker-actor prefixes finds none. The examples themselves don't change.

**Not a duplicate.** I searched open PRs for `APPOConfig`,
`IMPALAConfig`, doctest, and Gloo. #67775 is the only match. It changes
the second, Tune-based example in each of these docstrings and doesn't
touch the first example or `BUILD.bazel`.

## Testing

- `pre-commit run --files python/ray/rllib/BUILD.bazel`: all hooks pass,
including buildifier and buildifier-lint.
- On macOS arm64 with a Ray nightly wheel, master's `appo.py` and
`impala.py`, and Ray's default doctest plugin: `pytest -p
default_doctest_pytest_plugin --doctest-modules --noconftest
ray/rllib/algorithms/appo/appo.py ray/rllib/algorithms/impala/impala.py`
passes with and without `RAY_LOG_TO_DRIVER=0` (2 passed each time). The
Gloo line doesn't appear on macOS, so this run shows the change doesn't
break the examples but doesn't reproduce the failure. This PR's
premerge, which runs the full RLlib doctest target on Linux, is the real
check.

🤖 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]>
@pseudo-rnd-thoughts
pseudo-rnd-thoughts merged commit 721eb6f into master Nov 6, 2026
6 checks passed
@pseudo-rnd-thoughts
pseudo-rnd-thoughts deleted the doc-1914-rllib-get-truncateds-fix branch November 6, 2026 11:44
WiemKhlifi pushed a commit to WiemKhlifi/ray that referenced this pull request Nov 6, 2026
…inates

When every agent is done and at least one of them terminated, Case 2 in
`add_env_step()` declares the episode terminated (ray-project#67863). That flag was then
copied onto every agent with data on that step, so agents that were only
truncated (e.g. by a time limit, also when the env sends
`truncateds["__all__"]=True`) ended up both terminated and truncated. PPO/GAE,
DQN/SAC replay and v-trace then dropped their value bootstrap.

An agent is now marked terminated only by its own flag, by the env's
`terminateds["__all__"]`, or by the episode's terminated flag if it is not
truncated. This is the per-agent propagation ray-project#67863 left as a known
limitation.

Also drop this branch's `get_truncateds()` change (covered by ray-project#67627) and move
the tests into `test_add_env_step_all_agents_done_terminated_vs_truncated`.

Signed-off-by: Wiem Khlifi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation go add ONLY when ready to merge, run all tests rllib RLlib related issues skip-gpu-tests Skips GPU tests for PRs that trigger them due to overly broad rules.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants