Reviewer · Concurrency
Guard shared concurrent state
When code runs across threads, tasks, or coroutines, protect any state that is read and written by more than one execution path, and make sure background work cannot outlive the scope that owns the shared state it touches.
When code runs across threads, tasks, or coroutines, protect any state that is read and written by more than one execution path, and make sure background work cannot outlive the scope that owns the shared state it touches.
Concretely:
- Check-then-act sequences on shared containers (e.g. “is this key already warned/cached?” then insert) are not safe just because the underlying container is thread-safe for single operations. Wrap the check and the mutation in an explicit lock so the invariant you advertise (e.g. “exactly one warning per key”) holds by construction, not by timing luck.
- Snapshotting shared mutable state (e.g.
self.__dict__.copy()) only prevents “changed during iteration” errors; it does not give you a consistent point-in-time view. Say so in the docstring/comment rather than letting callers assume a stronger guarantee than what is actually provided. - When spawning concurrent work (
asyncio.ensure_future,ThreadPoolExecutor, etc.) that writes into shared/owning state (a conversation object, an agent’s memory, etc.), always cancel and await any still-pending tasks in afinallyblock before returning or re-raising. Otherwise, cancellation or an exception on the awaiting side leaves orphaned work running, which keeps mutating state the caller believes is no longer in use. - When an object is reused across concurrent/multiple logical “runs” (e.g. a shared agent instance invoked by different clients), explicitly isolate per-run state. Don’t rely on an implicit or hardcoded list of “helpers that happen to hold state today” — document and enforce which components must be reset, cloned, or reinitialized per invocation, so a newly added stateful helper doesn’t silently leak state across concurrent callers.
- Any loop that drains a queue fed by another thread/task must have a bound (max items or max size per iteration). An unbounded drain lets a fast producer grow memory or downstream payloads (e.g. a conversation transcript) without limit.
Example — cleaning up spawned tasks on cancellation:
async def arun(self, task: str):
runs = [asyncio.ensure_future(run_agent(agent)) for agent in self.agents]
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()
Without the finally cleanup, cancelling arun (e.g. via asyncio.wait_for) leaves the per-agent coroutines running and still writing into self.conversation after the caller has moved on.