Repository navigation
fix: eliminate TOCTOU race in EventService.send_message - #3160
Conversation
send_message(run=True) checked execution_status then created an untracked fire-and-forget task without holding _run_lock. Two concurrent calls could both see != RUNNING and start parallel runs of the same conversation. Delegate to self.run() which already wraps the check-and-dispatch in _run_lock, tracks the task in _run_task, and includes proper cleanup (callback waiting, state publishing). If the conversation is already running, the ValueError is silently caught — the message was already sent. Fixes #3147 Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
all-hands-bot
left a comment
There was a problem hiding this comment.
Taste Rating: 🟢 Good taste - Elegantly eliminates code duplication and fixes a real race condition by delegating to self.run(), which already handles status check, locking, task tracking, and cleanup correctly.
The Fix: The TOCTOU race was real - two concurrent send_message(run=True) calls could both see the conversation as non-running and start parallel run() executions. The fix consolidates all run logic into a single code path protected by _run_lock. Net -19 lines is excellent.
Eval Risk Note: Per repo guidelines, changes to loop logic require eval evidence. While this is a clear correctness improvement (fixing a concurrency bug), I'm flagging for human review to follow policy. The fix should make behavior more predictable, not less, but verification is prudent for changes in this area.
[IMPROVEMENT OPPORTUNITY]
- See inline comment on test clarity
[RISK ASSESSMENT]
- Overall PR
⚠️ Risk Assessment: 🟡 MEDIUM
This is a well-executed bug fix that simplifies the codebase and fixes a real race condition. The change is localized and well-tested. However, it modifies execution loop control flow (preventing duplicate concurrent runs), which per repo policy requires human verification.
Recommendation: Request a human maintainer to run lightweight evals to verify no performance regression, particularly for scenarios with concurrent message sending.
VERDICT:
⏸️ Awaiting eval verification: Core implementation is sound and improves correctness, but needs human verification with lightweight evals per repo policy for loop logic changes.
KEY INSIGHT:
Excellent refactoring that eliminates special-case code and fixes a race condition by consolidating duplicate logic into a single, correct implementation.
Improve this review? If any feedback above seems incorrect or irrelevant to this repository, you can teach the reviewer to do better:
- Add a
.agents/skills/custom-codereview-guide.mdfile to your branch (or edit it if one already exists) with the/codereviewtrigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.- Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
- When your PR is merged, the guideline file goes through normal code review by repository maintainers.
Resolve with AI? Install the iterate skill in your agent and run
/iterateto automatically drive this PR through CI, review, and QA until it's merge-ready.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The PR successfully eliminates the TOCTOU race condition in send_message(run=True) by delegating to the properly-locked run() method. All 73 event_service tests pass, and the fix achieves its stated goal without introducing regressions.
Does this PR achieve its stated goal?
Yes. The PR's goal was to fix a time-of-check/time-of-use race condition where two concurrent send_message(run=True) calls could both see the conversation as non-running and start parallel conversation.run() executions. The fix achieves this by replacing the inline, unlocked check-and-dispatch logic (lines 380-400 in the old code) with delegation to self.run(), which wraps the check + task creation in _run_lock (lines 672-682). This makes the check-and-set operation atomic and prevents the race. The approach is cleaner, reduces code duplication (-19 net lines), and adds proper task tracking and cleanup that the fire-and-forget pattern lacked.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully |
| CI Status | ✅ All critical tests passing (agent-server-tests, sdk-tests, pre-commit, etc.) |
| Functional Verification | ✅ All 73 event_service tests pass; fix verified through code analysis and test execution |
Functional Verification
Test 1: Verify all event_service tests pass with the fix
Command:
cd /home/runner/work/software-agent-sdk/software-agent-sdk/pr-repo
source .venv/bin/activate
OPENHANDS_SUPPRESS_BANNER=1 python -m pytest tests/agent_server/test_event_service.py -xResult:
======================== 73 passed, 5 warnings in 3.47s ========================
Interpretation: All 73 tests in the event_service test suite pass, including the 3 tests that were modified to match the new delegation pattern:
test_send_message_with_run_true_agent_already_running- Verifies that when the conversation is already running,send_message(run=True)delegates torun(), which raisesValueError, which is caught, andconversation.run()is not invoked a second time.test_send_message_with_run_true_agent_idle- Verifies that when the conversation is idle,send_message(run=True)successfully delegates torun(), which creates a tracked background task (_run_task).test_send_message_with_run_true_logs_exception- Verifies that exceptions during background execution are logged byrun()'s error handler.
This confirms no regressions were introduced and the new behavior matches expectations.
Test 2: Code analysis — compare old vs. new implementation
Old code (main branch, lines 380-400):
if run:
run = (
await self._get_execution_status() # ← CHECK (no lock!)
!= ConversationExecutionStatus.RUNNING
)
if run:
conversation = self._conversation
async def _run_with_error_handling():
try:
await loop.run_in_executor(None, conversation.run) # ← USE (no lock!)
except Exception:
logger.exception("Error during conversation run from send_message")
loop.create_task(_run_with_error_handling()) # ← Fire-and-forget (untracked!)Problem identified: The check at line 382-383 and the task creation at line 400 are NOT protected by any lock. Two concurrent callers can both pass the check and both create tasks.
New code (PR branch, lines 380-385):
if run:
try:
await self.run() # ← Delegate to run() which has proper locking!
except ValueError:
# Already running or inactive — message was sent, skip run.
passFix verified: The new code delegates to self.run(), which wraps the check + task creation in async with self._run_lock: (line 672). The lock makes the check-and-set atomic:
async def run(self):
if not self._conversation:
raise ValueError("inactive_service")
# Use lock to make check-and-set atomic, preventing race conditions
async with self._run_lock: # ← LOCK acquired!
if (
await self._get_execution_status() # ← CHECK (locked)
== ConversationExecutionStatus.RUNNING
):
raise ValueError("conversation_already_running")
# Check if there's already a running task
if self._run_task is not None and not self._run_task.done():
raise ValueError("conversation_already_running")
# Start run in background
self._run_task = loop.create_task(_run_and_publish()) # ← USE (locked, tracked!)Interpretation: The fix correctly eliminates the race condition. The second caller will acquire the lock, see that status == RUNNING or _run_task is not done, raise ValueError, which send_message catches and ignores. Only one conversation.run() execution proceeds.
Test 3: Verify specific race-condition tests pass
Command:
cd /home/runner/work/software-agent-sdk/software-agent-sdk/pr-repo
source .venv/bin/activate
OPENHANDS_SUPPRESS_BANNER=1 python -m pytest tests/agent_server/test_event_service.py \
-k "test_send_message_with_run_true" -xvsResult:
tests/agent_server/test_event_service.py::TestEventServiceSendMessage::test_send_message_with_run_true_agent_already_running PASSED
tests/agent_server/test_event_service.py::TestEventServiceSendMessage::test_send_message_with_run_true_agent_idle PASSED
tests/agent_server/test_event_service.py::TestEventServiceSendMessage::test_send_message_with_run_true_logs_exception PASSED
================= 3 passed, 70 deselected, 5 warnings in 0.20s =================
Interpretation: All three tests that directly exercise the send_message(run=True) code path pass. These tests verify:
- When already running,
run()is not called again (no duplicate execution) - When idle,
run()creates a tracked background task - Exceptions are properly logged
This confirms the fix works as intended.
Issues Found
None.
Address review feedback: set event_service._run_task to an active task so the already-running precondition is explicit at both the conversation state level and the EventService task level. Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
Taste Rating: 🟢 Good taste - Elegant fix that eliminates code duplication and properly handles the TOCTOU race by delegating to the existing run() method.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟢 LOW
This is a focused concurrency bug fix in infrastructure code. The delegation pattern consolidates duplicate logic into a single, properly-locked code path. All 73 tests pass and the external API is unchanged.
VERDICT:
✅ Worth merging: Clean fix that eliminates the race condition and reduces code complexity.
KEY INSIGHT:
The old "fire-and-forget" pattern wasn't intentional - it was the bug. Delegating to run() gives you proper locking, task tracking, and cleanup for free.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The TOCTOU race condition in EventService.send_message(run=True) is successfully eliminated. Verified with concurrent execution tests showing the fix prevents duplicate runs.
Does this PR achieve its stated goal?
Yes. The PR fixes the time-of-check/time-of-use race where two concurrent send_message(run=True) calls could both start parallel conversation.run() executions. I reproduced the race on the commit before the fix (2 runs started) and verified it's eliminated on this PR (only 1 run started). The fix delegates to self.run() which uses _run_lock to make the check-and-set atomic, exactly as described in the PR.
| Phase | Result |
|---|---|
| Environment Setup | ✅ Dependencies installed, all 73 tests pass |
| CI Status | ✅ All checks passing (pre-commit, API breakage, tests, binary builds) |
| Functional Verification | ✅ Race condition reproduced before fix, eliminated after fix |
Functional Verification
Test 1: Reproduce the Race Condition (Before Fix)
Step 1 — Establish baseline (commit b24f248, before the fix):
Checked out the parent commit before the fix and examined the old code:
async def send_message(self, message: Message, run: bool = False):
if not self._conversation:
raise ValueError("inactive_service")
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self._conversation.send_message, message)
if run:
run = (
await self._get_execution_status() # Check without lock!
!= ConversationExecutionStatus.RUNNING
)
if run:
conversation = self._conversation
async def _run_with_error_handling():
try:
await loop.run_in_executor(None, conversation.run)
except Exception:
logger.exception("Error during conversation run from send_message")
# Fire-and-forget: untracked task
loop.create_task(_run_with_error_handling())The bug: Lines 381-384 check execution status WITHOUT holding _run_lock. Two concurrent calls can both see "not running" and both create background tasks to start run().
Step 2 — Run concurrent test to reproduce the race:
Wrote a test that launches two send_message(run=True) calls concurrently with minimal delay (0.001s between calls) to simulate the race condition:
uv run python test_toctou_race.pyOutput:
Launching two concurrent send_message(run=True) calls...
→ Calling send_message('Message 1')
→ Calling send_message('Message 2')
(No tracked task - waiting for fire-and-forget tasks to complete...)
→ conversation.run() called (call #1)
→ conversation.run() called (call #2)
RESULTS:
- send_message() called: 2 times
- conversation.run() called: 2 times ← RACE CONDITION!
Result: Both calls started run() — the race condition exists in the old code.
Test 2: Verify the Fix (After Fix)
Step 1 — Apply the PR's changes:
Checked out the PR branch (fix/3147-send-message-toctou-race) and examined the new code:
async def send_message(self, message: Message, run: bool = False):
if not self._conversation:
raise ValueError("inactive_service")
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self._conversation.send_message, message)
if run:
try:
await self.run() # Delegates to run() which has proper locking!
except ValueError:
# Already running or inactive — message was sent, skip run.
passThe fix: Lines 381-385 delegate to self.run(), which uses _run_lock (line 672) to atomically check status and create a tracked task.
Step 2 — Re-run the same concurrent test with the fix:
uv run python test_toctou_race.pyOutput:
Launching two concurrent send_message(run=True) calls...
→ Calling send_message('Message 1')
→ Calling send_message('Message 2')
→ conversation.run() called (call #1)
RESULTS:
- send_message() called: 2 times
- conversation.run() called: 1 times ← FIXED!
✅ SUCCESS: Race condition is FIXED!
→ Both messages were sent
→ Only ONE run was started (no duplicate runs)
→ The fix correctly prevents TOCTOU race
Result: Only ONE run was started. The second send_message call encountered the ValueError (already running) and skipped the run, exactly as intended.
Test 3: Existing Test Suite
Ran all 73 tests in tests/agent_server/test_event_service.py:
uv run pytest tests/agent_server/test_event_service.py -vResult: All 73 tests PASSED ✅
The updated tests now verify:
test_send_message_with_run_true_agent_already_running: Confirms the second call skips run when already runningtest_send_message_with_run_true_agent_idle: Confirms run is started when idletest_send_message_with_run_true_logs_exception: Confirms error handling works viarun()'s cleanup
Issues Found
None.
Replace try/except/pass with suppress(ValueError) for cleaner exception handling when run() raises due to already-running state. Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Summary
send_message(run=True)had a time-of-check/time-of-use race condition: it checkedexecution_status != RUNNINGthen created an untracked fire-and-forget task — all without holding_run_lock. Two concurrentsend_messagecalls could both see the conversation as non-running and start parallelconversation.run()executions.Root cause
event_service.py:380-400— the status check and task dispatch were outside any lock. The existingrun()method already solved this correctly withasync with self._run_lock:, butsend_messagehad its own independent, unprotected code path.Fix
Replace the inline check-and-dispatch with delegation to
self.run(), catchingValueErrorwhen the conversation is already running. This:run()wraps check + dispatch in_run_lockrun()assigns to_run_task, enabling the double-guard (execution_status+_run_task.done())run()'sfinallyblock waits for pending callbacks and publishes state updates — the old fire-and-forget skipped thisThe change is 5 lines of production code (net -19 lines).
Verification
test_event_service.pytests passFixes #3147
This PR was created by an AI agent (OpenHands) on behalf of @csmith49.
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:b5fad88-pythonRun
All tags pushed for this build
About Multi-Architecture Support
b5fad88-python) is a multi-arch manifest supporting both amd64 and arm64b5fad88-python-amd64) are also available if needed