Skip to content

fix(mcp): keep a name's attach lock only while it is in use - #97

Merged
gopaljigaur merged 3 commits into
mainfrom
fix/mcp-lock-growth
Oct 15, 2026
Merged

gopaljigaur merged 3 commits into
mainfrom
fix/mcp-lock-growth

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

MCPClient.attach and detach took a per name lock with setdefault and never removed it, so the lock map grew with every name ever passed in (10,000 detaches of unknown names left 10,051 locks), and aclose() detached every one of them.

What changed

  • MCPClient._locks is a weakref.WeakValueDictionary. Every task holding or waiting on a name's lock keeps a strong reference to it, so the entry stays while any of them is in it, and a caller arriving while a woken waiter still runs gets the same lock. After that the entry is collected; a waiter cancelled while waiting can delay this while something retains its traceback. attach and detach still take it with setdefault.
  • aclose() detaches the attached servers plus the names with a lock in use (an attach or detach in flight), so it still waits for a pending attach.
  • Kept per name locks over one client wide lock: a client wide lock would serialize concurrent attaches of different servers, each of which may take up to connect_timeout.

Tests

  • 10,000 detaches of unknown names leave the lock map empty.
  • Attach/detach cycles, including a concurrent attach and detach of one name, leave no idle lock entry and one live session for the one attached server.
  • A caller that arrives after the holder leaves, before the woken waiter is done, waits for that waiter. The scenario fails when the entry is dropped on release.
  • The existing race tests (concurrent attach, detach waiting for attach, cancelled detach, aclose with a pending attach) now also assert the map is empty afterwards.
  • Checked by a script outside the suite: 10,000 unknown detaches plus 20 rounds of concurrent attach/detach leave open fds, asyncio tasks and child processes at their starting count.

Closes #84

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

The counting is correct and aclose() is correct, but the stdlib already does this bookkeeping, and the one race the counter exists for has no test.

Verified

  • uv run pytest 399 passed, pre-commit and mypy cyclops clean.
  • The 4 changed or new TestAttachDetach tests fail against main's client.py and pass here; 5 repeated runs with -W error::ResourceWarning all passed.
  • Stress script with a fake connection: 200 seeds of 400 staggered attach/detach calls over 5 names, a third of them cancelled at random points (including while waiting), then aclose() racing fresh attaches. No two tasks were ever inside one name's critical section, the map ends empty, no servers or tasks left over, on 3.10, 3.12 and 3.14. The same harness reports violations for a fresh lock per call and for dropping the entry on release, so it does catch broken locking.
  • Real servers: 10 rounds of 12 concurrent attach/detach calls on one shared name plus 3 others, one cancelled per round, then aclose() with two attaches pending. Open fds, child processes and tasks are back at their starting count.
  • aclose() over _connections plus _locks is right: attached servers have no lock entry once their attach returns, and a name that only shows up in _locks is mid attach or detach. Changing it to _connections alone makes test_aclose_waits_for_pending_attach fail.

Findings

  1. weakref.WeakValueDictionary gives the same guarantee without Counter or the context manager (inline).
  2. The counter's own guarantee is untested: dropping the entry on release with waiters still queued passes every TestAttachDetach test (inline).

Comment thread cyclops/mcp/client.py Resolved
Comment thread tests/test_mcp_client.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Both earlier threads are addressed in the code at 684dbb5: _locks is a weakref.WeakValueDictionary, attach and detach take the lock with setdefault as on main, contextlib, Counter, _lock_users and _lock are gone, and test_late_caller_waits_for_a_woken_waiter is in. One wording nit inline; nothing else.

Verified

  • uv run pytest 400 passed, pre-commit and mypy cyclops clean; test_mcp_client.py 56 passed on 3.10.
  • The 5 changed or new TestAttachDetach tests fail against main's client.py and pass here; 5 repeated runs with -W error::ResourceWarning all passed.
  • Stress script (fake connection, 200 seeds of 400 staggered attach/detach calls over 5 names, a third cancelled at random points, then aclose() racing fresh attaches): no overlap in any name's critical section, map empty, no servers or tasks left, on 3.10, 3.12 and 3.14.
  • Real servers: 10 rounds of 12 concurrent attach/detach calls with one cancelled per round, then aclose() with two attaches pending. Open fds, child processes and tasks return to their starting count.
  • aclose() with weak entries: [*self._connections, *self._locks] builds the list in one synchronous step, and WeakValueDictionary iteration defers removals made during it, so an entry vanishing mid iteration cannot raise. A name that vanishes after the list is built gets a fresh lock in detach(), which ignores unknown names. 50 runs of aclose() over 2,000 entries held only by cyclic garbage, with the GC threshold at 1, ran clean and left the map empty.
  • Test internals: the len(client._locks) == 0 asserts are the only way to observe the growth, and the late caller test takes the lock with the same setdefault the client uses, which is the least it can reach for. Dropping the entry inside detach() also fails two existing tests, so the attach/detach path is covered as well.

Comment thread cyclops/mcp/client.py Resolved
attach and detach took a per name lock with setdefault and never removed
it, so the map grew with every name ever seen and aclose detached all of
them. The lock entry now lives while a task holds or awaits it, and
aclose detaches attached servers and ones still attaching or detaching.
Each holder and waiter keeps a strong reference to its lock, so the weak
map drops a name's entry when the last one leaves. This replaces the hand
counted entries and adds a test with a caller arriving after the holder
leaves but before the woken waiter is done.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

No findings.

  • git range-diff against 684dbb5: both earlier commits are identical after the rebase (=), and the only new commit, b4e3484, changes the one comment line. git diff 684dbb5 b4e3484 -- cyclops/mcp tests/test_mcp_client.py is that same line, so #94 and #98 do not touch these files.
  • The comment now claims only what holds: every holder and waiter keeps a strong reference, so the entry stays while any of them is in it.
  • The body matches the code, including the note that a waiter cancelled while waiting can delay collection while its traceback is retained, which is what the leak runs showed.
  • uv run pytest 416 passed, pre-commit and mypy cyclops clean.

@gopaljigaur
gopaljigaur merged commit cb69c9e into main Oct 15, 2026
9 checks passed
@gopaljigaur
gopaljigaur deleted the fix/mcp-lock-growth branch October 15, 2026 02:20
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.

MCPClient keeps a lock for every server name it ever saw

1 participant