Ending an episode mid-move can drop the last tick's video frame; the test that covers it is flaky
Affects: main at e7d8eb41.
Test: tests/robot/test_trace_reporting.py::test_ending_the_episode_mid_move_ends_the_recording_with_the_ticks_played
Summary
The test fails intermittently on main (4 of 10 local runs). Investigating it turned up two separate things:
- The test's upper bound is off by one (a test race). It fails whenever the sim applies no further action between the agent abandoning the move and the episode ending, even though the recording is then correct.
- A real recording race in
DirectControl(a product issue). When a move is cancelled while a tick is being recorded, that tick's observation step reaches the trace but its video frame can be dropped, despitelossless_video=True("video frame N is always tick N"). The test's last assertion,frames_in(segments) == len(ticks), would catch this, but in those runs the bound assertion fails first.
Reproduce
for i in $(seq 1 20); do
uv run --python 3.12 --all-extras pytest -q -p no:cacheprovider \
"tests/robot/test_trace_reporting.py::test_ending_the_episode_mid_move_ends_the_recording_with_the_ticks_played" | tail -1
done
Typical failure:
> assert 3 <= len(ticks) < 1 + len(sim.actions)
E assert 4 < (1 + 3)
Evidence
I ran the test's own scenario as a probe that records counts instead of asserting: 200–300 runs per measurement, Linux, Python 3.12.
1. Bound (test race). Recorded ticks never exceed played ticks plus one, and ticks are always contiguous. A completed rollout records 1 + len(sim.actions) ticks, as test_a_camera_the_encoder_cannot_encode_costs_the_video_not_the_rollout asserts. The bound fails exactly when no extra action is applied after the agent gives up:
| Extra actions after the signal | Bound fails |
|---|---|
| 0 | 10 / 14 runs |
| ≥ 1 | 0 / 26 runs |
In the mismatched runs:
- All 4 frames were submitted to
SegmentEncoder, but the encoder dispatched only 3. The trace matches what was dispatched, so span export isn't the problem. - With instrumentation, every mismatched run (25/25) had a frame submitted after
SegmentEncoder.finalize(). No consistent run did (0/275). - The two calls are
TraceRecorder.record_observation(fromDirectControl._record) andTraceRecorder.close(fromDirectControl.end_episode), running concurrently in twoasyncio.to_threadworkers. - Every mismatch happened in a run where a
_record()await was cancelled. None happened without that cancellation (0/217 such runs).
Likely cause
DirectControl._record (hud/environment/robot/control.py ~696) holds self._recording while awaiting asyncio.to_thread(recorder.record_observation, ...). Cancelling the move cancels that await. The worker thread keeps running, but the async with exits and releases the lock. end_episode() then takes the lock and closes the recorder: the encoder's stop sentinel is queued before the still-running thread submits the tick's frame, so the frame is never encoded.
Catching the cancellation and waiting for the thread in the same task did not help (35/300 mismatches). That's consistent with the cancellation being re-delivered to the waiting task; FastMCP runs tools under anyio, whose cancellation is level-triggered.
Running the tick's recording, lock included, in its own task and awaiting it with asyncio.shield removed the mismatch entirely (0/300), and tests/robot still passed (45 passed):
async def _record(self, obs: dict[str, Any]) -> None:
"""Stream one tick's state and camera frames to the trace."""
if (recorder := self._recorder) is not None:
# Its own task, so cancelling the move cannot release the lock mid-tick.
await asyncio.shield(asyncio.ensure_future(self._record_tick(recorder, obs)))
async def _record_tick(self, recorder: TraceRecorder, obs: dict[str, Any]) -> None:
async with self._recording:
if recorder is self._recorder: # the episode may have ended while waiting
await asyncio.to_thread(recorder.record_observation, obs["data"], tick=self._tick)
self._tick += 1
Suggested changes
- Test: relax the bound to
3 <= len(ticks) <= 1 + len(sim.actions), which is the documented "ticks played" invariant, and keep theframes_in(segments) == len(ticks)check. - Product: keep a tick's recording atomic with respect to
end_episode, for example as above.
With only the bound relaxed, the test would still fail in roughly 6–8% of runs, on the frame check. With the product change as well, the frame check held in 300/300 runs.
Impact
Telemetry fidelity only. When an episode ends by cancelling a move (an agent abandoning it, a timeout, Ctrl-C), the final observation can appear in the trace without its video frame, so the video ends one frame short of the state stream. Rewards and grading are unaffected.
Happy to open a PR with both changes if that's useful.
Closing as not planned. The test's bound is fixed in #788, which also stops the test from cancelling the move. A move is only cancelled mid-way when a run times out or is cancelled, and losing that run's last video frame doesn't justify changing the recording path. Thanks for the detailed investigation.
Got it, thanks for reviewing, Jaideep!