Skip to content

perf(gateway): run multi-memory prime, recall, and contradiction reads concurrently - #785

Merged
richard-epsilla merged 4 commits into
HarnessRouter:mainfrom
aarush323:perf/memory-concurrent-fanout
Dec 1, 2026
Merged

richard-epsilla merged 4 commits into
HarnessRouter:mainfrom
aarush323:perf/memory-concurrent-fanout

Conversation

@aarush323

Copy link
Copy Markdown
Contributor

Fixes #784

The bug

On main (e120bb7b), prime, recall, and _other_sides in gateway/memory_plane.py run their engine calls one after another. Provider.recall_many in the same file already states the intended pattern: "The default asks every memory at once (a person's task searches the person's memory and the agent's, and one after the other was the sum of two searches)" (gateway/memory_plane.py:262).

To see it, call GET /v1/memories/{mid}/prime?depth=1 on a memory with three children through a fixture provider that waits 150 ms per prime call. The request takes 0.615 s (median of 3 runs), the sum of four sequential calls. recall queries each provider group sequentially, and _other_sides at the end of every recall (turn-start recall included) awaits provider_of and .get() sequentially for each contradicting record. Repeated binds also repeat credential lookups, and ReMe.bind() health checks when its cache is cold. This is a latency problem only. It has no security impact.

Expected behavior

prime, multi-group recall, and _other_sides bind each unique (provider, org, workspace) once, all at the same time, and then run their engine reads at the same time. Latency follows the slowest call, not the sum. Outputs, tie ordering, budget truncation, degraded order, abstain, and which error is raised stay the same as on main.

The fix

I added _provider_key and _bind_all to gateway/memory_plane.py. _bind_all binds each unique (provider, org, workspace) once with asyncio.gather. Adding org to recall's old (provider, workspace) key matches provider_of binding by org; callers pass memories from one org today, so groups do not change. Only read paths use _bind_all, because the shared Announced wrapper keeps the first memory's _above, and only write methods read it.

prime, recall, and _other_sides gather engine calls with return_exceptions=True, walk results in input order to raise the same first error as main (see the tests), and recall passes its bound map directly to _other_sides. _other_sides deduplicates (where, other) pairs in insertion order and checks other in have before raising, so an engine error on a pair the sequential loop never reached does not fail the recall.

The raised error matches main, though a failing batch makes more engine calls than before: prime binds every key and primes memories before the first bind failure even if an earlier call fails, recall binds and queries every group even when an earlier group fails, errors surface after the slowest call finishes, and _other_sides discards extra active copies read concurrently. No new concurrency cap is added: prime is bounded by RECALL_MAX_MEMORIES = 200 via reach_below, and _other_sides by the recall limit (100 max) times each result's contradicts references, matching Provider.recall_many. The wire API, Provider.recall_many, gateway/memory_routes.py, and gateway/memory_local.py do not change.

gateway/tests/test_memory_fanout_perf.py adds 8 tests covering concurrent barriers for prime, recall, and _other_sides, TestClient latency on GET /v1/memories/{mid}/prime?depth=1, single-memory parity, bind deduplication and reuse, stable order and budget cuts, degraded and abstain, contradiction deduplication and skipped-pair engine-error isolation, input-order error precedence over 20 seeded runs, and zero leftover tasks after outer cancellation.

Verification

Python 3.12.3.

python -m pytest gateway/tests/test_memory_fanout_perf.py -q
python -m pytest gateway/tests -q
python -m pytest scripts/support-matrix/memories -q
Check Before (e120bb7b) After
gateway/tests/test_memory_fanout_perf.py 2 passed, 6 failed 8 passed (5 runs in a row)
GET /v1/memories/{mid}/prime?depth=1 fixture route (4 x 150 ms) 0.615 s median (0.615, 0.617, 0.615 s) 0.164 s median (0.158, 0.164, 0.169 s; 3.75x faster)
gateway/tests — 3337 passed, 27 skipped
scripts/support-matrix/memories — 9 passed

The 2 that pass on main test error precedence/cancellation and contradiction dedup/skipped-pair isolation, which sequential code already satisfies. In gateway/tests, the 27 skipped tests require services or keys absent on this machine: 14 need PostgreSQL on localhost:55432, 1 needs MySQL on localhost:33306, 10 need MEM0_API_KEY, and 2 need HR_TEST_TOKENROUTER_KEY. I did not run runner/tests, the ui/ checks, or a container build, because the change touches only gateway/memory_plane.py and its new test file.

@vercel

vercel Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
unified-harness-protocol Ready Ready Preview Dec 1, 2026 5:57pm UTC

Request Review

@STiFLeR7 STiFLeR7 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

prime() now waits for later reads after its result is already an error (gateway/memory_plane.py:1047 at 13bda6c).

I ran the actual memory_plane.prime() with an in-memory provider and two memories. The first read raises MemoryError(503, "memory_unavailable", ...) immediately. The second waits on an asyncio.Event. On main (4f8b14d), prime() returns memory_unavailable before the second read starts. On this head, after 500 ms the second read is still waiting and prime() cannot return. Releasing the event immediately reveals the first error. No gateway or vendor service is needed to reproduce this.

The PR preserves which error wins, but gather(..., return_exceptions=True) delays that error until every read settles. An unrelated slow provider can now hold a known failure until its timeout. Could we keep concurrent starts and process outcomes in input order, cancelling and draining unfinished siblings when the first error in that order is known? That would preserve the current error precedence and prompt failure. The same wait-for-later-reads pattern is present in recall().

@aarush323

Copy link
Copy Markdown
Contributor Author

@STiFLeR7 Thanks for the repro.

Pushed follow-up commit 74148a4 to keep concurrent starts while processing outcomes in input order and cancelling/draining remaining siblings as soon as the first error in that order (or an outer/AnyIO cancellation) occurs:

  • Added _cancel_tasks() (cancels every task synchronously before await asyncio.gather(*tasks, return_exceptions=True)) and _gather_ordered().
  • prime() starts unique key provider_of binds once, shields them across sibling reads, awaits read tasks in input order, and cancels/drains both tasks and bind_tasks together in finally:.
  • recall() uses _gather_ordered() for key binds and recall_many() calls; _other_sides() cancels skipped duplicate pairs inline and drains remaining .get() tasks in finally:.

Added test_first_error_cancels_and_drains_unfinished_siblings_promptly covering your immediate-failure repro (fails promptly without waiting for the slow sibling), in-flight sibling/bind cancellations across prime, recall, and _other_sides, plus an anyio.move_on_after bind-cancellation case. Re-ran gateway/tests/test_memory_fanout_perf.py (5/5 × 9 passed, first run with -W error::pytest.PytestUnraisableExceptionWarning), scripts/support-matrix/memories (9 passed), and gateway/tests (3338 passed, 27 environment-gated skips).

prime now reads a set's memories in overlap instead of one by one. A set can hold up to RECALL_MAX_MEMORIES (200),
and an engine (a vendor's API, a small self-hosted server) should not get every read of one turn at once. A
semaphore caps the overlapping reads at PRIME_CONCURRENCY = 8; the order, the budget and the first-error-in-order
behaviour are unchanged. The test reads 24 memories and sees the peak at exactly 8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@richard-epsilla richard-epsilla 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.

Reviewed from first principles and verified on a test instance as part of 0.43.1 (release branch rel/0.43.1, built and run live).

@richard-epsilla
richard-epsilla merged commit 28b472c into HarnessRouter:main Dec 1, 2026
12 checks passed

This branch was successfully deployed

1 active deployment
Preview — 838b083e Deployed Dec 1, 2026 by vercel[bot]
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.

memories: prime, recall, and _other_sides run multi-memory engine calls sequentially

3 participants