Reviewer · Concurrency
Concurrent task isolation
When code runs across multiple threads or async tasks, default to isolating mutable state per task rather than sharing it: clone or snapshot any object (agents, helpers, counters) that holds per-run state before handing it to a concurrent worker, so writes from one task can never land on another task's or the caller's shared instance (e.g. clone-per-task...
When code runs across multiple threads or async tasks, default to isolating mutable state per task rather than sharing it: clone or snapshot any object (agents, helpers, counters) that holds per-run state before handing it to a concurrent worker, so writes from one task can never land on another task’s or the caller’s shared instance (e.g. clone-per-task execution in run_concurrently callers, or copying per-request state before invoking a shared tool/agent). When state truly must be shared (e.g. a dedup/warning set, a counter), protect every check-then-act sequence with an explicit lock — don’t rely on “unlikely under the GIL” timing, since free-threaded builds and even normal thread switches can produce duplicate or corrupted results. Any list of “things that hold back-references to shared state and must be isolated/cloned” is a correctness-critical invariant, not an implementation detail — keep it in one place (ideally derived from the stateful object itself via a classmethod/hook) and cover it with a test so a newly added stateful helper can’t silently reintroduce a leak. For async dispatch logic that decides whether to await a coroutine directly vs. offload to a thread, test both branches explicitly (including subclass overrides and instance-level attribute overrides), since a wrong branch degrades concurrency silently with no test failure. Finally, when gathering or awaiting a group of spawned tasks, ensure cancellation (e.g. from a timeout) actually cancels and awaits every spawned task in a finally block before returning — otherwise cancelled tasks keep running in the background and can mutate state (like a conversation log) after the caller believes the operation is done:
python
try:
await asyncio.gather(*runs, return_exceptions=True)
for run, agent in zip(runs, self.agents):
self._record(agent, run.result)
finally:
for run in runs:
if not run.done():
run.cancel()
await asyncio.gather(*runs, return_exceptions=True)
self.workspace.save_conversation()
</description>
</invoke>