Repository navigation
fix(mcp): keep a name's attach lock only while it is in use - #97
Merged
Merged
Conversation
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
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 pytest399 passed,pre-commitandmypy cyclopsclean.- The 4 changed or new
TestAttachDetachtests fail against main'sclient.pyand pass here; 5 repeated runs with-W error::ResourceWarningall 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_connectionsplus_locksis right: attached servers have no lock entry once their attach returns, and a name that only shows up in_locksis mid attach or detach. Changing it to_connectionsalone makestest_aclose_waits_for_pending_attachfail.
Findings
weakref.WeakValueDictionarygives the same guarantee withoutCounteror the context manager (inline).- The counter's own guarantee is untested: dropping the entry on release with waiters still queued passes every
TestAttachDetachtest (inline).
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
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 pytest400 passed,pre-commitandmypy cyclopsclean;test_mcp_client.py56 passed on 3.10.- The 5 changed or new
TestAttachDetachtests fail against main'sclient.pyand pass here; 5 repeated runs with-W error::ResourceWarningall 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, andWeakValueDictionaryiteration 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 indetach(), which ignores unknown names. 50 runs ofaclose()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) == 0asserts are the only way to observe the growth, and the late caller test takes the lock with the samesetdefaultthe client uses, which is the least it can reach for. Dropping the entry insidedetach()also fails two existing tests, so the attach/detach path is covered as well.
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
force-pushed
the
fix/mcp-lock-growth
branch
from
October 15, 2026 02:15
684dbb5 to
b4e3484
Compare
gopaljigaur
commented
Oct 15, 2026
gopaljigaur
left a comment
Owner
Author
There was a problem hiding this comment.
No findings.
git range-diffagainst 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.pyis 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 pytest416 passed,pre-commitandmypy cyclopsclean.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
MCPClient.attachanddetachtook a per name lock withsetdefaultand never removed it, so the lock map grew with every name ever passed in (10,000 detaches of unknown names left 10,051 locks), andaclose()detached every one of them.What changed
MCPClient._locksis aweakref.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.attachanddetachstill take it withsetdefault.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.connect_timeout.Tests
Closes #84