Nov 21, 2026·9 min read·1 visit
A race condition (CWE-362) in the McpClientSearchAdapter component of memtomem-stm (< 0.1.34) causes concurrent RPC failures to trigger duplicate reconnect storms and allows mid-flight task cancellations to leave interrupted transport streams reusable. Upgrading to version 0.1.34 resolves the flaw by introducing monotonic session generation tracking and flight coalescing.
CVE-2026-77331 (GHSA-72jh-722p-rqr3) is a concurrency and session-state synchronization vulnerability in memtomem-stm, a short-term memory proxy gateway for AI agents. In versions 0.1.2 prior to 0.1.34, concurrent Model Context Protocol (MCP) Remote Procedure Call (RPC) failures or mid-flight task cancellations can initiate duplicate reconnect loops and permit dirty or cancelled transport sessions to be reused. This deficiency results in session-state integrity loss and local service degradation.
memtomem-stm operates as a short-term memory (STM) proxy gateway that provides proactive memory surfacing for AI agent runtimes. To retrieve and store context, the proxy communicates asynchronously with an upstream Long-Term Memory (LTM) server over the Model Context Protocol (MCP). This communication layer is managed by the McpClientSearchAdapter class located in src/memtomem_stm/surfacing/mcp_client.py.
Because AI agent pipelines frequently execute concurrent memory lookups and tool invocations, McpClientSearchAdapter shares a single underlying ClientSession instance across multiple Python asyncio coroutines. When transport errors or task timeouts occur, the adapter is responsible for tearing down the broken transport and establishing a clean replacement session before subsequent queries proceed.
In memtomem-stm versions from 0.1.2 through 0.1.33, the session recovery mechanism lacks proper synchronization and epoch tracking, categorized under CWE-362 (Concurrent Execution using Shared Resource with Improper Synchronization). The flaw manifests in two distinct subcases: uncoordinated duplicate reconnections during concurrent RPC failures (affecting versions >= 0.1.24, < 0.1.34), and the reuse of dirty transport streams following an asyncio.CancelledError during a post-reconnect retry (affecting the full range >= 0.1.2, < 0.1.34).
When triggered, these synchronization failures degrade the integrity and availability of the local memory proxy. Duplicate reconnects tear down healthy replacement sessions in a cascading loop, while mid-flight cancellations leave the underlying protocol stream in a half-open or desynchronized state for subsequent callers.
The primary root cause of CVE-2026-77331 is the use of a non-versioned boolean flag (self._needs_reconnect) to track the lifecycle and health of a shared asynchronous transport session. Without a monotonic generation counter binding an active ClientSession to the specific coroutines using it, the adapter cannot distinguish between a failure on an already-replaced session and a failure on a newly established session.
When an upstream disconnect or httpx.TransportError occurs while multiple surfacing queries (search, increment_access, scratch_list) are in flight, every failing coroutine catches the exception and calls await self._reconnect(). Although an internal owner task serializes the execution of _reconnect(), it does not deduplicate requests originating from the same broken session instance. Once the first coroutine's reconnect completes and publishes a healthy replacement session, the second coroutine's queued reconnect immediately executes, tearing down the newly created session and initiating an unnecessary replacement cycle.
A secondary synchronization defect occurs when the calling runtime cancels an in-flight memory operation via asyncio.wait_for or task cancellation. If an asyncio.CancelledError interrupts session.call_tool() during the initial request or during a post-reconnect retry, the coroutine aborts midway through reading or writing to the MCP transport stream.
In vulnerable versions, the post-reconnect retry path does not wrap the second session.call_tool() invocation in a cancellation handler that marks the replacement session as dirty. Furthermore, because cancellation handling does not verify whether self._session has already been rotated by another coroutine, a delayed cancellation in one coroutine can erroneously flag a newer, healthy session for reconnection, or leave a half-read replacement stream active for subsequent RPCs.
Prior to commit 761db1802df7ce4881ff4c3acee6d674925da498, McpClientSearchAdapter initialized a single boolean flag self._needs_reconnect = False and processed reconnections unconditionally. During an RPC execution such as search(), the vulnerable code path handled cancellations and transport errors without verifying session identity:
# Vulnerable implementation prior to v0.1.34
if self._needs_reconnect:
await self._reconnect()
session = self._session
try:
raw = await session.call_tool("mem_search", args)
except asyncio.CancelledError:
# Unconditionally marks adapter for reconnect regardless of active session version
self._needs_reconnect = True
raise
except Exception as exc:
logger.warning("MCP transport error, attempting reconnect: %s", exc)
# Every concurrent failing caller executes an independent reconnect cycle
await self._reconnect()
if self._session is None:
return [], False, "error"
try:
# Post-reconnect retry: if CancelledError occurs here, the replacement
# session is interrupted mid-stream but self._needs_reconnect remains False
raw = await self._session.call_tool("mem_search", args)
except Exception as retry_exc:
return [], False, "error"Commit 761db1802df7ce4881ff4c3acee6d674925da498 resolves both defects by introducing generational epoch tracking (_generation and _dirty_generation), a dedicated synchronization lock (_reconnect_lock), and a dictionary of active reconnection tasks (_reconnect_flights). Each time _connect() establishes a new ClientSession, self._generation is incremented by 1.
# Patched initialization and helpers in v0.1.34
self._needs_reconnect = False
self._generation = 0
self._dirty_generation: int | None = None
self._reconnect_lock = asyncio.Lock()
self._reconnect_flights: dict[int, asyncio.Task[None]] = {}
def _current_session_generation(self) -> tuple[ClientSession | None, int]:
return self._session, self._generation
def _mark_dirty(self, session: ClientSession, generation: int) -> None:
"""Mark only the currently published session generation as dirty."""
if self._session is session and self._generation == generation:
self._dirty_generation = generation
self._needs_reconnect = True
async def _rpc(
self, session: ClientSession, generation: int, tool: str, args: dict[str, Any]
) -> Any:
"""Run one RPC and dirty only the session cancelled mid-call."""
try:
return await session.call_tool(tool, args)
except asyncio.CancelledError:
self._mark_dirty(session, generation)
raiseTo eliminate reconnect storms, the patch replaces direct calls to self._reconnect() with self._shared_reconnect(generation). When multiple coroutines fail on generation $N$, _shared_reconnect() acquires _reconnect_lock, checks if a reconnect task for generation $N$ already exists in _reconnect_flights, and creates one only if absent. All callers for generation $N$ then await the same task via asyncio.shield(flight), ensuring that cancellation of one waiting caller does not abort the underlying recovery task for other callers.
async def _shared_reconnect(self, generation: int) -> None:
"""Join the single reconnect flight for a dirty generation."""
async with self._reconnect_lock:
flight = self._reconnect_flights.get(generation)
if flight is None or flight.done():
flight = asyncio.create_task(
self._reconnect_generation(generation),
name=f"ltm-reconnect-generation-{generation}",
)
def finish(completed: asyncio.Future[None]) -> None:
self._finish_reconnect_flight(generation, completed)
flight.add_done_callback(finish)
self._reconnect_flights[generation] = flight
await asyncio.shield(flight)In addition, _reconnect(expected_generation) now validates that self._generation == expected_generation inside the owner task before tearing down the connection. All initial and post-reconnect tool invocations are routed through self._rpc(session, generation, ...), guaranteeing that an asyncio.CancelledError during a retry properly marks the replacement generation as dirty.
> [!NOTE]
> The fix is complete across all exposed adapter methods (search, increment_access, and scratch_list), and stop() drains any in-flight tasks in _reconnect_flights prior to shutdown to prevent orphaned background tasks.
Triggering CVE-2026-77331 does not require network-borne malicious payloads; rather, it is triggered locally within the agent runtime pipeline when concurrent memory surfacing tasks encounter transient upstream LTM failures or aggressive caller-side timeouts. An attacker or untrusted workload with low-privilege access capable of issuing parallel queries through the agent runtime can intentionally induce high concurrency and rapid task cancellations to destabilize the proxy.
To trigger the duplicate-reconnect subcase, at least two coroutines must concurrently invoke an adapter method (such as adapter.search()) while referencing the same active ClientSession (generation 1). When the underlying transport fails (for example, throwing a ConnectionError), both coroutines enter their exception handlers simultaneously.
In the regression test suite added in tests/test_mcp_client_reconnect.py, the maintainers demonstrate this behavior deterministically using asyncio.Event gates:
first = asyncio.create_task(adapter.search("first"))
second = asyncio.create_task(adapter.search("second"))
await asyncio.wait_for(both_started.wait(), timeout=1.0)
release_failures.set()
await asyncio.wait_for(reconnect_started.wait(), timeout=1.0)
for _ in range(10):
await asyncio.sleep(0)
# In patched versions, only generation 1 is queued once:
assert reconnect_generations == [1]On vulnerable versions (0.1.24 through 0.1.33), both first and second invoke _reconnect(), causing reconnect_generations to record two distinct teardown-and-connect cycles. The second cycle destroys the replacement session created by the first cycle, potentially interrupting first's post-reconnect retry.
To trigger the cancellation-recovery subcase, a caller wraps an adapter request in a timeout or cancels the task after an initial transport failure has already triggered _reconnect(), while the post-reconnect retry (session.call_tool) is still awaiting an upstream response:
retry_Task = asyncio.create_task(adapter.search("cancel during retry"))
await asyncio.wait_for(retry_started.wait(), timeout=1.0)
retry_Task.cancel()
with pytest.raises(asyncio.CancelledError):
await retry_TaskIn versions prior to 0.1.34, cancelling retry_Task during the retry phase raises asyncio.CancelledError directly out of search() without setting _needs_reconnect = True. When a subsequent coroutine calls adapter.search("after cancelled retry"), it reuses the interrupted replacement session whose stream state was left incomplete by the aborted RPC.
CVE-2026-77331 carries a CVSS v4.0 base score of 2.0 (Low) with the vector CVSS:4.0/AV:L/AC:H/AT:P/PR:L/UI:N/VC:N/VI:L/VA:L/SC:N/SI:N/SA:L. The low severity reflects the local attack vector (AV:L), high attack complexity (AC:H), and the requirement for specific asynchronous timing conditions (AT:P) during concurrent memory operations.
The primary impact on the vulnerable system is limited integrity loss (VI:L) and availability degradation (VA:L), with a corresponding low availability impact on subsequent downstream agent components (SA:L). There is no direct confidentiality impact (VC:N, SC:N), as the race condition does not expose unauthorized memory records across tenant boundaries.
From an operational standpoint, reusing a transport session after an interrupted protocol exchange causes framing or state desynchronization between the memtomem-stm proxy and the upstream MCP server. Subsequent tool calls executing over the dirty transport may receive mismatched responses, fail protocol validation, or silently drop memory surfacing updates (increment_access).
During a duplicate-reconnect storm, cascading teardown loops repeatedly reset active sessions while sibling coroutines are executing post-reconnect retries. This causes valid memory lookups to fail and fall back to degraded error states (return [], False, "error"), stalling the AI agent's short-term memory surfacing pipeline.
The authoritative remediation is to upgrade memtomem-stm to version 0.1.34 or later, which incorporates commit 761db1802df7ce4881ff4c3acee6d674925da498. Packages can be updated via PyPI using standard Python package managers:
pip install --upgrade "memtomem-stm>=0.1.34"If an immediate upgrade is not possible in production deployments, operators can apply two configuration and architectural workarounds to reduce the probability of hitting the race window:
McpClientSearchAdapter methods (search, increment_access, scratch_list) using an external asyncio.Semaphore(1) wrapper at the application call site. Serializing requests prevents multiple callers from triggering concurrent reconnects or overlapping with post-reconnect retries.asyncio.wait_for() cancellation windows. Allowing RPCs to complete or fail cleanly at the underlying HTTP/transport layer prevents mid-stream asyncio.CancelledError interruptions from leaving replacement sessions in a half-open state.Security and engineering teams can monitor application logs for indicators of reconnect storms by alerting on tight bursts of the warning messages MCP transport error, attempting reconnect: or Lazy reconnect after mid-RPC cancellation failed: within a short time interval.
CVSS:4.0/AV:L/AC:H/AT:P/PR:L/UI:N/VC:N/VI:L/VA:L/SC:N/SI:N/SA:L| Product | Affected Versions | Fixed Version |
|---|---|---|
memtomem-stm memtomem | >= 0.1.2, < 0.1.34 | 0.1.34 |
| Attribute | Detail |
|---|---|
| Vulnerability ID | CVE-2026-77331 / GHSA-72jh-722p-rqr3 |
| Weakness Class | CWE-362 (Race Condition / Improper Synchronization) |
| CVSS v4.0 Score | 2.0 (Low) - CVSS:4.0/AV:L/AC:H/AT:P/PR:L/UI:N/VC:N/VI:L/VA:L/SC:N/SI:N/SA:L |
| Affected Component | McpClientSearchAdapter (src/memtomem_stm/surfacing/mcp_client.py) |
| Vulnerable Versions | memtomem-stm >= 0.1.2, < 0.1.34 |
| Patched Version | memtomem-stm 0.1.34 |
| Primary Impact | Duplicate reconnect storms, dirty transport session reuse, and local service degradation |
| Exploit / KEV Status | Unit Test PoC Available / Not Listed in CISA KEV |
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
svglib versions prior to 2.3.1 contain an uncontrolled resource consumption vulnerability in the svg2rlg() renderer. When parsing SVG documents containing nested <use> elements, SvgRenderer.renderUse() recursively resolves and deep-copies referenced subtrees without enforcing a global expansion limit. Although the library detects and blocks direct circular references, an attacker can construct an acyclic directed reference graph with high fan-out (an SVG analogue to the XML Billion Laughs attack). Processing a crafted SVG payload of less than 2 KB triggers exponential node duplication, exhausting CPU and memory in applications that convert user-supplied SVGs or HTML documents embedding SVG content.
CVE-2026-132277 (also tracked as GHSA-q87h-c5m7-659j) is an uncontrolled resource consumption and algorithmic complexity vulnerability in the Inscriptis Python library (versions 2.0.0 through 2.7.5). When rendering sibling HTML table elements inside a block-level parent container, the parser fails to pop the parent block's inline padding prefix from the internal canvas prefix stack upon closing the block. Consequently, each subsequent sibling table inherits and accumulates the indentation prefixes of all preceding tables. This causes the output string length and memory allocation of get_text() to grow quadratically with the number of sibling tables, allowing a compact untrusted HTML payload to trigger denial of service via memory exhaustion.
CVE-2026-132276 (GHSA-53pm-wgxf-c6qf) is an algorithmic complexity and Regular Expression Denial of Service (ReDoS) vulnerability in the Python wcmatch wildcard and glob matching library prior to version 11.2. Under default flags, matching a non-matching attacker-controlled filename against a static developer-defined pattern containing multiple star (*) wildcards separated by literal delimiters causes polynomial-time backtracking O(n^k) in the compiled regular expression. A single 255-byte filename evaluated against a 5-star pattern consumes approximately 86 seconds of 100% CPU time, allowing unauthenticated attackers to induce severe availability degradation.
CVE-2026-122244 (GHSA-r2q3-7m4h-63qg) is a high-severity cross-privilege Stored Cross-Site Scripting (XSS) vulnerability in Budibase prior to version 3.50.0. The flaw occurs due to defective character escaping in the JSON formatter utility combined with raw HTML rendering via Svelte's {@html} directive in the Budibase Builder interface. A low-privileged application user or an unauthenticated form visitor can store malicious HTML markup in a shared datasource, which subsequently executes arbitrary JavaScript in the browser session of an administrator or application builder inspecting Handlebars formula bindings.
A tenant-confusion vulnerability in the user initialization endpoint of the Budibase worker service (prior to version 3.50.0) allows unauthenticated remote attackers to bypass the one-time administrative setup guard. By supplying arbitrary tenant identifiers in POST requests to /api/global/users/init, an attacker can force the underlying CouchDB datastore to dynamically provision unlimited tenant databases and persist latent global administrator accounts. This results in datastore resource exhaustion, denial of service, and unauthorized administrative account creation inside non-default tenant contexts.
Paymenter versions prior to 1.5.7 contain an arbitrary method invocation vulnerability within the base Livewire component architecture. The application includes a legacy trait, HasConfirmation, inside app/Livewire/Component.php, which is inherited across 36 client-facing Livewire components. This trait exposes a public remote procedure call (RPC) endpoint named executeConfirmedAction without access controls or method allowlisting. Remote attackers can invoke arbitrary methods on any inheriting component, including Livewire's internal fill() method, enabling them to bypass #[Locked] property protections and manipulate internal component state and hydrated Eloquent models.