Skip to content

fix: eliminate TOCTOU race in EventService.send_message - #3160

Merged
csmith49 merged 5 commits into
mainfrom
fix/3147-send-message-toctou-race
May 12, 2026
Merged

csmith49 merged 5 commits into
mainfrom
fix/3147-send-message-toctou-race

Conversation

@csmith49

@csmith49 csmith49 commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

send_message(run=True) had a time-of-check/time-of-use race condition: it checked execution_status != RUNNING then created an untracked fire-and-forget task — all without holding _run_lock. Two concurrent send_message calls could both see the conversation as non-running and start parallel conversation.run() executions.

Root cause

event_service.py:380-400 — the status check and task dispatch were outside any lock. The existing run() method already solved this correctly with async with self._run_lock:, but send_message had its own independent, unprotected code path.

Fix

Replace the inline check-and-dispatch with delegation to self.run(), catching ValueError when the conversation is already running. This:

  • Fixes the race: run() wraps check + dispatch in _run_lock
  • Tracks the task: run() assigns to _run_task, enabling the double-guard (execution_status + _run_task.done())
  • Adds proper cleanup: run()'s finally block waits for pending callbacks and publishes state updates — the old fire-and-forget skipped this
  • Reduces code: 19 insertions, 38 deletions — eliminates duplicated dispatch logic

The change is 5 lines of production code (net -19 lines).

Verification

  • All 73 test_event_service.py tests pass
  • All pre-commit hooks pass (ruff, pyright, etc.)
  • Updated 3 tests to match the delegation pattern

Fixes #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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:b5fad88-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-b5fad88-python \
  ghcr.io/openhands/agent-server:b5fad88-python

All tags pushed for this build

ghcr.io/openhands/agent-server:b5fad88-golang-amd64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-golang-amd64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-golang-amd64
ghcr.io/openhands/agent-server:b5fad88-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:b5fad88-golang-arm64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-golang-arm64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-golang-arm64
ghcr.io/openhands/agent-server:b5fad88-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:b5fad88-java-amd64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-java-amd64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-java-amd64
ghcr.io/openhands/agent-server:b5fad88-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:b5fad88-java-arm64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-java-arm64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-java-arm64
ghcr.io/openhands/agent-server:b5fad88-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:b5fad88-python-amd64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-python-amd64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-python-amd64
ghcr.io/openhands/agent-server:b5fad88-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:b5fad88-python-arm64
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-python-arm64
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-python-arm64
ghcr.io/openhands/agent-server:b5fad88-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:b5fad88-golang
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-golang
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-golang
ghcr.io/openhands/agent-server:b5fad88-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:b5fad88-java
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-java
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-java
ghcr.io/openhands/agent-server:b5fad88-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:b5fad88-python
ghcr.io/openhands/agent-server:b5fad88128cf44ca71f89d25fbad0dffe9caf891-python
ghcr.io/openhands/agent-server:fix-3147-send-message-toctou-race-python
ghcr.io/openhands/agent-server:b5fad88-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., b5fad88-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., b5fad88-python-amd64) are also available if needed

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>
@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   event_service.py4319577%78–79, 104, 108, 111–112, 116–117, 124, 134–138, 141–144, 164, 268, 285, 326, 336, 360–361, 365, 373, 376, 424, 426, 430–432, 436, 445–446, 448, 452, 458, 460, 490–495, 521, 524, 575, 579, 725, 727–728, 732, 746–748, 750, 754–757, 761–764, 772–775, 823–824, 826–833, 835–836, 845–846, 848–849, 856–857, 859–860, 880, 886, 892, 901–902
TOTAL267011164156% 

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Add a .agents/skills/custom-codereview-guide.md file to your branch (or edit it if one already exists) with the /codereview trigger and the context the reviewer is missing. See the customization docs for the required frontmatter format.
  2. Re-request a review - the reviewer reads guidelines from the PR branch, so your changes take effect immediately.
  3. 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 /iterate to automatically drive this PR through CI, review, and QA until it's merge-ready.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 -x

Result:

======================== 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 to run(), which raises ValueError, which is caught, and conversation.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 to run(), which creates a tracked background task (_run_task).
  • test_send_message_with_run_true_logs_exception - Verifies that exceptions during background execution are logged by run()'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.
        pass

Fix 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" -xvs

Result:

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:

  1. When already running, run() is not called again (no duplicate execution)
  2. When idle, run() creates a tracked background task
  3. 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>
@csmith49
csmith49 requested a review from all-hands-bot May 11, 2026 16:41

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.py

Output:

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.
            pass

The 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.py

Output:

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 -v

Result: 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 running
  • test_send_message_with_run_true_agent_idle: Confirms run is started when idle
  • test_send_message_with_run_true_logs_exception: Confirms error handling works via run()'s cleanup

Issues Found

None.

@csmith49
csmith49 requested a review from VascoSch92 May 11, 2026 22:15
csmith49 and others added 2 commits May 12, 2026 07:21
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>
@csmith49
csmith49 merged commit 0c71e9d into main May 12, 2026
29 of 30 checks passed
@csmith49
csmith49 deleted the fix/3147-send-message-toctou-race branch May 12, 2026 13:31
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
Co-authored-by: openhands <openhands@all-hands.dev>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: send_message fire-and-forget TOCTOU race

3 participants