Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
76 changes: 58 additions & 18 deletions gateway/memory_plane.py
Original file line number Diff line number Diff line change
Expand Up @@ -1013,13 +1013,45 @@ 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 _bind_all(memories: list[dict], *, raise_first: bool = True) -> dict:
"""Bind each unique (provider, org, workspace) once, concurrently. Reads only: the shared
Announced wrapper carries the first memory's `_above`, which only writes consult."""
first: dict[tuple[str, str, str], dict] = {}
for m in memories:
first.setdefault(_provider_key(m), m)
keys = list(first)
got = await asyncio.gather(*(provider_of(first[k]) for k in keys), return_exceptions=True)
if raise_first:
for item in got:
if isinstance(item, BaseException):
raise item
return dict(zip(keys, got))


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."""
rows, truncated = [], False
bound = await _bind_all(memories, raise_first=False)
runnable, first_bind_err = [], None
for m in memories:
got = await (await provider_of(m)).prime(str(m["id"]), budget)
prov = bound[_provider_key(m)]
if isinstance(prov, BaseException):
first_bind_err = prov
break
runnable.append((m, prov))
answers = await asyncio.gather(*(p.prime(str(m["id"]), budget) for m, p in runnable), return_exceptions=True)
for got in answers:
if isinstance(got, BaseException):
raise got
if first_bind_err is not None:
raise first_bind_err
rows, truncated = [], False
for (m, _), got in zip(runnable, 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 +1070,19 @@ 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]]] = {}
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"]))
mids_by_key.setdefault(_provider_key(m), []).append(str(m["id"]))
bound = await _bind_all(memories)
groups = [(bound[k], mids) for k, mids in mids_by_key.items()]
answers = await asyncio.gather(*(prov.recall_many(mids, req) for prov, mids in groups), return_exceptions=True)
for res in answers:
if isinstance(res, BaseException):
raise res
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 +1091,33 @@ 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:
continue
rec = await (await provider_of(by_id[where])).get(where, other)
if rec and rec.get("status") == "active":
have.add(other)
out.append({"record": rec, "memory_id": where, "score": None, "why": ["contradicts"]})
if ref.get("rel") == "contradicts" and other not in have and where in by_id:
wanted.setdefault((where, other))
fetched = await asyncio.gather(*(bound[_provider_key(by_id[w])].get(w, o) for w, o in wanted), return_exceptions=True)
out: list[dict] = []
for (where, other), rec in zip(wanted, fetched):
if other in have:
continue
if isinstance(rec, BaseException):
raise rec
if rec and rec.get("status") == "active":
have.add(other)
out.append({"record": rec, "memory_id": where, "score": None, "why": ["contradicts"]})
return out


Expand Down
Loading
Loading