Skip to content

Fix get_free_port_pair() TOCTOU race condition#1013

Open
zch42 wants to merge 2 commits intoPrimeIntellect-ai:mainfrom
zch42:fix/free-port-pair-race
Open

Fix get_free_port_pair() TOCTOU race condition#1013
zch42 wants to merge 2 commits intoPrimeIntellect-ai:mainfrom
zch42:fix/free-port-pair-race

Conversation

@zch42
Copy link

@zch42 zch42 commented Mar 12, 2026

Description

Hold port reservation sockets open to prevent the OS from reassigning ports between discovery and ZMQ bind. Fixes #1012.

Changes

  • Keep sockets alive in a module-level list instead of closing them on return
  • Set SO_REUSEADDR so child ZMQ processes can still bind the same ports

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Test improvement

Testing

  • All existing tests pass when running uv run pytest locally.
  • New tests have been added to cover the changes

Checklist

  • My code follows the style guidelines of this project as outlined in AGENTS.md
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Additional Notes


Note

Medium Risk
Changes low-level socket/port allocation behavior and intentionally holds sockets open, which could cause port exhaustion or unexpected reuse semantics if called repeatedly.

Overview
Fixes a TOCTOU race in get_free_port_pair() by reserving the discovered ports: it now creates sockets with SO_REUSEADDR, binds both port and port+1, and keeps those sockets alive in a module-level _reserved_sockets list instead of closing them immediately.

Adds _make_reusable_socket() helper to centralize reusable/bind logic and updates retry behavior to explicitly close partially-acquired sockets on failure.

Written by Cursor Bugbot for commit 21d6f13. This will update automatically on new commits. Configure here.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

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.

get_free_port_pair() TOCTOU race causes port collision with multiple env servers

1 participant