Skip to content

[RLlib] Fix MultiAgentEpisode declaring termination when a new agent joins as the last known agent terminates - #66913

Open
Akshaay1 wants to merge 4 commits into
ray-project:masterfrom
Akshaay1:fix/multi-agent-episode-new-agent-termination
Open

Akshaay1 wants to merge 4 commits into
ray-project:masterfrom
Akshaay1:fix/multi-agent-episode-new-agent-termination

Conversation

@Akshaay1

@Akshaay1 Akshaay1 commented Oct 10, 2026 •

Copy link
Copy Markdown

Description

MultiAgentEpisode.add_env_step() declares the episode terminated when a new agent's first observation arrives on the same step that the last registered agent terminates, even though the env reports terminateds["__all__"] = False. The "Case 2" check (all agents done) only looks at self.agent_ids, and the newcomer is added to self.agent_episodes later in the same method, so it can't keep the episode open. Its observation is discarded, and with batch_mode="truncate_episodes" the MultiAgentEnvRunner then steps the still-live env with an empty action dict.

This applies the fix @WiemKhlifi suggested in #66781: count agents observed in this step in the Case 2 check. Following review, it uses the dicts' key views to avoid building temporary sets:

if all(
    aid in agents_done
    for aid in self.agent_episodes.keys() | observations.keys()
):

A newcomer that's already terminated or truncated on its first observation is in agents_done, so an episode where every agent is done still terminates as before.

Related issues

Fixes #66781

Additional information

Tests. test_add_env_step_new_agent_joining_as_last_agent_terminates in rllib/env/tests/test_multi_agent_episode.py has two cases:

  1. The reproduction from [RLlib] MultiAgentEpisode marks the episode terminated when a new agent joins on the step the last registered agent terminates (despite __all__=False) #66781. On master it fails at assertFalse(episode.is_terminated); with this change it passes, with agent_ids == {"a0", "a1"} and __all__ False.
  2. The newcomer is already done on its first observation and the env reports __all__=False. The episode must still terminate. This catches an over-broad fix that skips Case 2 whenever a new agent appears; I checked that such a variant fails it.
pytest python/ray/rllib/env/tests/test_multi_agent_episode.py python/ray/rllib/env/tests/test_multi_agent_env_runner.py

Run against the Ray 2.59.0 wheel (with torch) with this branch's multi_agent_episode.py: 24 passed (19 + 5) on this branch, and on master only the new test fails. black (22.10.0) and ruff (0.8.4) are clean on both files.

Not a duplicate. No other PR references #66781 or changes this check (gh pr list --state open --search "66781 in:body" and an area search on MultiAgentEpisode termination). @WiemKhlifi offered to open a PR in the issue, and @mayankdas2005 asked to take it on 2026-10-08; neither has opened one. @WiemKhlifi, if you'd rather submit your own, I'm happy to close this one.

AI assistance. AI assistance was used to write this change and its test. I reviewed every changed line and ran the tests above.

@Akshaay1
Akshaay1 marked this pull request as ready for review October 10, 2026 06:48
@Akshaay1
Akshaay1 requested a review from a team as a code owner October 10, 2026 06:48

@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 ensures that newly observed agents in the current step are considered when determining if a multi-agent episode should terminate, preventing premature termination when a new agent joins as another terminates. A unit test was added to verify this behavior. The review feedback suggests optimizing the termination check by using dictionary key views to avoid intermediate set allocations.

if all(aid in set(agents_done) for aid in self.agent_ids):
# this episode as terminated. Agents observed for the first time in this step
# count as well: they are only added to `self.agent_episodes` further below.
if all(aid in agents_done for aid in self.agent_ids | set(observations)):

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

We can optimize this check by using dictionary key views directly instead of constructing intermediate sets. Since self.agent_episodes and observations are both dictionaries, their .keys() views support set operations (like union |) in Python 3. Using self.agent_episodes.keys() | observations.keys() avoids calling the self.agent_ids property (which creates a new set) and calling set(observations) (which creates another set), reducing unnecessary object allocations in add_env_step, which is called at every environment step.

Suggested change
if all(aid in agents_done for aid in self.agent_ids | set(observations)):
if all(aid in agents_done for aid in self.agent_episodes.keys() | observations.keys()):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Applied in a090655: the check now uses self.agent_episodes.keys() | observations.keys(), which avoids the two temporary sets. Behavior is the same, since agent_ids is set(self.agent_episodes.keys()). test_multi_agent_episode.py (19) and test_multi_agent_env_runner.py (5) pass.

@WiemKhlifi WiemKhlifi 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.

Thanks for the contribution, LGTM. The fix matches what I had locally, and I already checked the fix against my custom environment.

One suggestion for the test: a fix that only checks observations.keys() passes both cases here but would end the episode on any step where no agent observes.
This case catches it and passes on this branch:

def test_add_env_step_without_observations_keeps_episode_open(self):
    # A step in which the only live agent does not observe must not end the episode.
    episode = MultiAgentEpisode(agent_module_ids={"a0": "p"})
    episode.add_env_reset(observations={"a0": np.zeros(1)}, infos={"a0": {}})

    episode.add_env_step(
        observations={},
        actions={"a0": 0},
        rewards={},
        terminateds={"__all__": False},
        truncateds={"__all__": False},
    )

    self.assertFalse(episode.is_done)

Akshaay1 added a commit to Akshaay1/ray that referenced this pull request Oct 19, 2026
Guards against a Case 2 check that only considers agents observed in the
current step, which would end the episode whenever no agent observes.

Suggested-by review on ray-project#66913.

Signed-off-by: Akshaay <[email protected]>
@github-actions

github-actions Bot commented Nov 3, 2026

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 Nov 3, 2026
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]>
…joins as the last known agent terminates

self.agent_ids (== self.agent_episodes.keys()) is read before newly
observed agents are added to self.agent_episodes in add_env_step(), so
a brand-new agent's first observation arriving on the same env step
that finishes off all previously registered agents was invisible to
the Case 2 check. This made the episode terminate even though the env
reported terminateds["__all__"] = False and the new agent is alive.

Exclude agents observed for the first time this step (and not
themselves terminated/truncated) from the Case 2 'all known agents
done' check.

Signed-off-by: Akshaay <[email protected]>
…eproduction as the test

Count agents observed in this step in the Case 2 check, as suggested by
the issue reporter, instead of tracking newly joined live agents
separately. Behavior is unchanged.

The regression test now uses the reporter's reproduction, and the
"newcomer already done" case uses __all__=False so it exercises Case 2
rather than passing through the __all__ check.

Signed-off-by: Akshaay <[email protected]>
…check

Use self.agent_episodes.keys() | observations.keys() instead of the
self.agent_ids property and set(observations), as suggested by
gemini-code-assist on this PR. Dict key views support set union
directly, so this skips two intermediate set allocations without
changing behavior.

Signed-off-by: Akshaay <[email protected]>
Guards against a Case 2 check that only considers agents observed in the
current step, which would end the episode whenever no agent observes.

Suggested-by review on ray-project#66913.

Signed-off-by: Akshaay <[email protected]>
@Akshaay1
Akshaay1 force-pushed the fix/multi-agent-episode-new-agent-termination branch from f3e88a0 to 14b6002 Compare November 9, 2026 04:25
@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 Nov 9, 2026

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 rllib RLlib 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.

[RLlib] MultiAgentEpisode marks the episode terminated when a new agent joins on the step the last registered agent terminates (despite __all__=False)

2 participants