Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 72 additions & 14 deletions gateway/memory_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,13 +1013,58 @@ def within_budget(rows: list[dict], budget: int) -> dict:
return {"records": kept, "tokens": used, "truncated": cut}


def _provider_key(memory: dict) -> tuple[str, str, str]:
return (str(memory.get("provider") or ""), str(memory.get("org") or ""), str(memory.get("workspace") or "") or "default")


async def _cancel_tasks(tasks: list[asyncio.Task]) -> None:
if not tasks:
return
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)


# How many memories prime reads at once. A set can hold up to RECALL_MAX_MEMORIES; read one by one before, they now
# overlap, and an engine (a vendor's API, a small self-hosted server) should not get 200 reads from one turn at once.
PRIME_CONCURRENCY = 8


async def _gather_ordered(coros) -> list:
"""Run coroutines concurrently, returning results in input order; on the first error in
input order (or cancellation), cancel and drain unfinished siblings before raising."""
tasks = [asyncio.create_task(c) for c in coros]
try:
return [await t for t in tasks]
finally:
await _cancel_tasks(tasks)


async def prime(org: str, memories: list[dict], budget: int) -> dict:
"""The standing records of a set of memories, newest first, cut to one budget: each provider
is asked for its own, then the whole is ordered by when each was written and cut again, the
first always kept. Each record names the memory it is in."""
bind_tasks: dict[tuple[str, str, str], asyncio.Task] = {}
tasks: list[asyncio.Task] = []
slots = asyncio.Semaphore(PRIME_CONCURRENCY)

async def _prime_one(m: dict, bind_task: asyncio.Task) -> dict:
prov = await asyncio.shield(bind_task)
async with slots:
return await prov.prime(str(m["id"]), budget)

try:
# Read-only bind reuse: Announced._above is only consulted on writes.
for m in memories:
k = _provider_key(m)
if k not in bind_tasks:
bind_tasks[k] = asyncio.create_task(provider_of(m))
tasks = [asyncio.create_task(_prime_one(m, bind_tasks[_provider_key(m)])) for m in memories]
answers = [await t for t in tasks]
finally:
await _cancel_tasks([*tasks, *bind_tasks.values()])
rows, truncated = [], False
for m in memories:
got = await (await provider_of(m)).prime(str(m["id"]), budget)
for m, got in zip(memories, answers):
truncated = truncated or bool(got.get("truncated"))
# every provider's answer, whichever way it was read (a relayed server's among them): nothing an engine drew
rows += [(r, str(m["id"])) for r in got.get("records") or [] if not drawn_by_the_engine(r)]
Expand All @@ -1038,17 +1083,20 @@ async def prime(org: str, memories: list[dict], budget: int) -> dict:
async def recall(org: str, memories: list[dict], req: dict) -> dict:
"""One question over a set of memories the caller may read: grouped by the provider that keeps
each, asked once per provider, merged into one ranking. Each result names the memory it is in."""
groups: dict[tuple, tuple[Provider, list[str]]] = {}
first: dict[tuple[str, str, str], dict] = {}
mids_by_key: dict[tuple[str, str, str], list[str]] = {}
for m in memories:
key = (str(m.get("provider") or ""), str(m.get("workspace") or "") or "default")
if key not in groups:
groups[key] = (await provider_of(m), [])
groups[key][1].append(str(m["id"]))
k = _provider_key(m)
first.setdefault(k, m)
mids_by_key.setdefault(k, []).append(str(m["id"]))
# Read-only bind reuse: Announced._above is only consulted on writes.
bound = dict(zip(first, await _gather_ordered(provider_of(m) for m in first.values())))
groups = [(bound[k], mids) for k, mids in mids_by_key.items()]
answers = await _gather_ordered(prov.recall_many(mids, req) for prov, mids in groups)
results, degraded, abstains = [], [], []
asked = [s for s in ("query", "text", "filters") if req.get(s)]
for prov, mids in groups.values():
for (prov, _), res in zip(groups, answers):
signals = (prov.capabilities().get("recall") or {}).get("signals") or []
res = await prov.recall_many(mids, req)
results += res.get("results") or []
for d in (res.get("degraded") or []) + [f"{s}:not_supported" for s in asked if s not in signals]:
if d not in degraded:
Expand All @@ -1057,27 +1105,37 @@ async def recall(org: str, memories: list[dict], req: dict) -> dict:
results = [r for r in results if not is_probe(r.get("record") or {})]
results.sort(key=lambda x: -(x.get("score") or 0))
results = results[: int(req.get("limit") or 8)]
return {"results": results + await _other_sides(memories, results), "degraded": degraded,
return {"results": results + await _other_sides(memories, results, bound), "degraded": degraded,
"abstain": bool(abstains) and all(abstains)}


async def _other_sides(memories: list[dict], results: list[dict]) -> list[dict]:
async def _other_sides(memories: list[dict], results: list[dict], bound: dict) -> list[dict]:
"""A hit on one side of a disagreement brings the other, whichever provider keeps them, marked as
brought along and not counted against the limit: a reader should not act on half of one (§6.3)."""
by_id = {str(m["id"]): m for m in memories}
have = {str((r.get("record") or {}).get("id")) for r in results}
out: list[dict] = []
wanted: dict[tuple[str, str], None] = {}
for r in results:
here = str(r.get("memory_id") or "")
for ref in (r.get("record") or {}).get("references") or []:
other = str(ref.get("record_id") or "")
where = str(ref.get("memory_id") or here)
if ref.get("rel") != "contradicts" or other in have or where not in by_id:
if ref.get("rel") == "contradicts" and other not in have and where in by_id:
wanted.setdefault((where, other))
tasks: list[asyncio.Task] = []
out: list[dict] = []
try:
tasks = [asyncio.create_task(bound[_provider_key(by_id[w])].get(w, o)) for w, o in wanted]
for (where, other), task in zip(wanted, tasks):
if other in have:
task.cancel()
continue
rec = await (await provider_of(by_id[where])).get(where, other)
rec = await task
if rec and rec.get("status") == "active":
have.add(other)
out.append({"record": rec, "memory_id": where, "score": None, "why": ["contradicts"]})
finally:
await _cancel_tasks(tasks)
return out


Expand Down
Loading
Loading