Reviewer · Concurrency
Isolate or synchronize shared state
When code runs under threads, asyncio tasks, or any other concurrent execution context, treat every piece of mutable state that more than one caller can touch as a hazard until proven otherwise. Prefer eliminating the sharing over guarding it: give each concurrent run its own copy of the state it mutates (e.g. clone an agent before use in `majority_voting`,...
When code runs under threads, asyncio tasks, or any other concurrent execution context, treat every piece of mutable state that more than one caller can touch as a hazard until proven otherwise. Prefer eliminating the sharing over guarding it: give each concurrent run its own copy of the state it mutates (e.g. clone an agent before use in majority_voting, or route per-run holders like llm_manager/tool_manager/autonomous_loop through a per-request copy mechanism rather than a hardcoded list that silently misses future additions) rather than relying on callers to remember which attributes are “safe.”
Where sharing is unavoidable (e.g. a module-level warning cache), protect the full check-then-act sequence with an explicit lock instead of relying on timing:
_warned_lock = threading.Lock()
def _warn_once(name: str) -> None:
with _warned_lock:
if name in _warned:
return
_warned.add(name)
logger.warning(...)
Also make sure concurrent task lifecycles are fully resolved before an operation is considered done. If an asyncio.gather can be cancelled (timeouts, caller cancellation), cancel and await every spawned task in a finally block so none keep running and mutating state the caller has already replaced:
try:
await asyncio.gather(*runs, return_exceptions=True)
finally:
for run in runs:
if not run.done():
run.cancel()
await asyncio.gather(*runs, return_exceptions=True)
Finally, bound anything a concurrent producer can feed into your consumer (e.g. draining a steering queue) so a fast or malicious producer cannot grow memory or context unboundedly; cap items processed per iteration instead of looping until empty. Add tests that exercise the concurrent paths (multiple threads/tasks hitting the same code) so races and leaks fail loudly instead of silently.