From be55db106151fef2d0f678349918e37a6aa78045 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sat, 5 Dec 2026 00:08:26 +0000 Subject: [PATCH] A revision lookup by id or by identity sends only the branch it has rows for Beside an `IN` over an empty list, ClickHouse 26.4 cannot prune the other branch by the sorting key or the `memory_id` index, and reads the whole namespace. `reads.live_revisions` builds its statement from the lists that name a row: ids alone, identities alone, or both joined by `OR`. The answer, the tenant and read-scope clauses and the `LIMIT` are the same on each. On 26.4 with 200,000 rows in one namespace, an identity-only call for two rows reads 256 rows where the joined statement reads 200,896, and an id-only call reads 9,728. A call that names rows both ways sends the joined statement and reads the namespace. The stubs of the namespace.audit and namespace.validate tests recognise the citation read by its select list, which every shape carries. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- server/memory/store/reads.py | 27 +++-- tests/analyzer/cases/legs.py | 14 ++- tests/analyzer/shapes.txt | 2 + tests/unit/test_live_revisions.py | 164 ++++++++++++++++++++++++++ tests/unit/test_namespace_audit.py | 4 +- tests/unit/test_namespace_validate.py | 2 +- 6 files changed, 195 insertions(+), 18 deletions(-) create mode 100644 tests/unit/test_live_revisions.py diff --git a/server/memory/store/reads.py b/server/memory/store/reads.py index 02d59c6a878..cfd70ed089a 100644 --- a/server/memory/store/reads.py +++ b/server/memory/store/reads.py @@ -1689,14 +1689,21 @@ async def live_revisions( if not memory_ids and not identities: return [] ch = ch or _default_client() - params: dict[str, Any] = { - "org": org, - "ns": namespace, - "ids": list(memory_ids), - "identities": list(identities), - # Each id and identity names one row. - "cap": len(memory_ids) + len(identities), - } + # Each id and identity names one row. + params: dict[str, Any] = {"org": org, "ns": namespace, "cap": len(memory_ids) + len(identities)} + # A branch is sent only for a list that names a row. Beside an `IN` over an empty + # list, a server that does not fold it away cannot prune the other branch by the + # sorting key or the memory_id index, and reads the whole namespace. + named: list[str] = [] + if memory_ids: + params["ids"] = list(memory_ids) + named.append("memory_id IN {ids:Array(UUID)}") + if identities: + params["identities"] = list(identities) + named.append( + "(agent, user_id, session_id, memory_key)" + " IN {identities:Array(Tuple(String, String, String, String))}" + ) # The id is selected under another name: an alias named memory_id would shadow the # column in WHERE. rows = await ch.query_all( @@ -1706,9 +1713,7 @@ async def live_revisions( agent, user_id, session_id, memory_type, source_class, updated_at FROM loom.memory FINAL WHERE org = {{org:String}} AND namespace = {{ns:String}} AND tombstoned_at IS NULL - AND (memory_id IN {{ids:Array(UUID)}} - OR (agent, user_id, session_id, memory_key) - IN {{identities:Array(Tuple(String, String, String, String))}}) + AND ({" OR ".join(named)}) {scope_and(scope, params)} LIMIT {{cap:UInt32}} """, diff --git a/tests/analyzer/cases/legs.py b/tests/analyzer/cases/legs.py index 4417c79519d..08c83bef8ab 100644 --- a/tests/analyzer/cases/legs.py +++ b/tests/analyzer/cases/legs.py @@ -492,13 +492,13 @@ async def _keys_and_fence(ch: RecordingCH, c: dict[str, Any]) -> None: async def _live_revisions(ch: RecordingCH, c: dict[str, Any]) -> None: from server.memory.store.reads import live_revisions - # namespace.audit / namespace.validate's citation read, by id and by identity + # namespace.audit / namespace.validate's citation read: by id, by identity, by both await live_revisions( ORG, NS, scope=WHOLE_NAMESPACE, - memory_ids=["00000000-0000-0000-0000-000000000001"], - identities=[(AGENT, "-", "-", "k")], + memory_ids=[] if c["named"] == "identity" else ["00000000-0000-0000-0000-000000000001"], + identities=[] if c["named"] == "id" else [(AGENT, "-", "-", "k")], hash_max_bytes=1 << 16, ch=ch, ) @@ -749,7 +749,13 @@ def cases() -> list[Case]: rows=_STUB_ROWS, ), Case("memory_repo.keys_and_fence", MR, _keys_and_fence, {}), - Case("memory_repo.live_revisions", MR, _live_revisions, {}, rows=_CITED_ROWS), + Case( + "memory_repo.live_revisions", + MR, + _live_revisions, + {"named": ("id", "identity", "both")}, + rows=_CITED_ROWS, + ), Case("deep_evidence", DE, _deep_evidence, {}), Case( "code_links.stale_of_served", diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 236c1044d36..486c7191228 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -2040,6 +2040,7 @@ dabe37717488 SELECT state_key, state_value, detail, updated_at FROM loom.code_in dae0d2378112 SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND user_id = {uid:String} AND tombstoned_at IS NULL dae4a1968b69 ALTER TABLE loom.context_blobs UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutat dae7125bf66f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- The content hash, for the read receipt of a hit this +db0473cb91f2 SELECT memory_key, toString(memory_id) AS id, version, sensitivity, value_len, redacted_at IS NOT NULL AS redacted, agent, user_id, session_id, memory_type, source_class, updated_at FROM loom.memory F db13fde1fa1b SELECT count() AS n FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL db1aefddf28d ALTER TABLE loom.document_blobs DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? db20b0dcab76 SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, created_at, valid_at, version, status FROM ( SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, t @@ -2371,6 +2372,7 @@ fc4aa7b41b6f ALTER TABLE loom.dataset_rows DELETE WHERE (org = {org:String} AND fc6c8b0fd1c4 SELECT c.session_id AS session_id, c.chunk_index AS chunk_index, c.parent_memory_key AS parent_memory_key, cosineDistance(c.embedding, {q:Array(Float32)}) AS distance FROM loom.memory_chunks AS c WHER fc77cdd5ec3e SELECT DISTINCT org, namespace, name, source_id, source_kind, owner_subject, connection_id FROM loom.knowledge_sources WHERE credential_mode = ? AND NOT (source_kind = ? OR kind = ? OR credential_mode fc8917f4e0b5 SELECT count() AS n FROM loom.memory_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL +fcaf7ecfaaf7 SELECT memory_key, toString(memory_id) AS id, version, sensitivity, value_len, redacted_at IS NOT NULL AS redacted, agent, user_id, session_id, memory_type, source_class, updated_at FROM loom.memory F fcb76bd55982 SELECT path, scope, symbol_ids, kind, start_line, end_line, content, embedding_model, shingles, uniqExact(path) OVER () AS admitted_files FROM ( SELECT path, scope, symbol_ids, kind, start_line, end_l fcf47e494773 SELECT count() AS n FROM loom.knowledge_group_members WHERE org = {org:String} AND namespace IN {ns:Array(String)} fd3c097c633d SELECT f AS path, uniqExact(pr_number) AS prs FROM loom.code_pr_history FINAL ARRAY JOIN files AS f WHERE org = {org:String} AND namespace = {ns:String} AND f IN {paths:Array(String)} AND merged_at > diff --git a/tests/unit/test_live_revisions.py b/tests/unit/test_live_revisions.py new file mode 100644 index 00000000000..7782494f900 --- /dev/null +++ b/tests/unit/test_live_revisions.py @@ -0,0 +1,164 @@ +"""`reads.live_revisions` names rows by id, by identity or by both: the branches its +statement carries for each call, and the rows each form returns on clickhouse-local +against the production table.""" + +from __future__ import annotations + +import re +from typing import Any + +import pytest + +from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters, scope_and +from server.memory.store.reads import RowKey, live_revisions +from tests.unit.ch_fake import RecordingCH +from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl + +OWN_U1 = ReadFilters(scope="own_user", user_id="u1", session_id=None) + +A1 = "00000000-0000-0000-0000-0000000000a1" +A2 = "00000000-0000-0000-0000-0000000000a2" +A3 = "00000000-0000-0000-0000-0000000000a3" +A4 = "00000000-0000-0000-0000-0000000000a4" +A5 = "00000000-0000-0000-0000-0000000000a5" +A6 = "00000000-0000-0000-0000-0000000000a6" + +# The list each `IN` of a statement reads. +_IN_LIST = re.compile(r"\bIN\s*\{(\w+):Array\(") + + +@pytest.mark.parametrize( + ("ids", "identities", "branches"), + [ + ([A1], [], {"ids"}), + ([], [("a", "u1", "s", "k2")], {"identities"}), + ([A1], [("a", "u1", "s", "k2")], {"ids", "identities"}), + ], +) +async def test_an_empty_list_sends_no_branch_for_it( + ids: list[str], identities: list[RowKey], branches: set[str] +) -> None: + """An `IN` over an empty list keeps the other branch from pruning by the key, so the + statement names only the lists that hold a row, inside the same tenant and read scope.""" + ch = RecordingCH(strict=False) + await live_revisions( + "o", + "n", + scope=OWN_U1, + memory_ids=ids, + identities=identities, + hash_max_bytes=0, + ch=ch, # type: ignore[arg-type] + ) + (sent,) = ch.calls + sql = " ".join(sent.sql.split()) + assert set(_IN_LIST.findall(sql)) == branches + assert [name for name in branches if not sent.params[name]] == [] + assert {"ids", "identities"} & sent.params.keys() == branches + assert (" OR " in sql) == (len(branches) == 2) + assert "WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL" in sql + assert scope_and(OWN_U1, {}).strip() in sql + assert sql.endswith("LIMIT {cap:UInt32}") + assert sent.params["cap"] == len(ids) + len(identities) + assert (sent.params["org"], sent.params["ns"], sent.params["scope_uid"]) == ("o", "n", "u1") + + +async def test_both_lists_empty_runs_no_statement() -> None: + """A call that names no row answers nothing without a round trip.""" + ch = RecordingCH() + rows = await live_revisions( + "o", + "n", + scope=WHOLE_NAMESPACE, + memory_ids=[], + identities=[], + hash_max_bytes=100, + ch=ch, # type: ignore[arg-type] + ) + assert rows == [] + assert ch.calls == [] + + +def _memory( + mid: str, namespace: str, user: str, key: str, version: int = 1, tombstoned: bool = False +) -> str: + gone = "'2026-01-02 00:00:00'" if tombstoned else "NULL" + return ( + "INSERT INTO loom.memory (org, namespace, agent, user_id, session_id, memory_key, " + "memory_id, value, version, tombstoned_at, created_at, updated_at) VALUES " + f"('o', '{namespace}', 'a', '{user}', 's', '{key}', '{mid}', 'v', {version}, {gone}, " + "'2026-01-01 00:00:00', '2026-01-01 00:00:00')" + ) + + +@pytest.fixture(scope="module") +def memory(tmp_path_factory: pytest.TempPathFactory) -> KeptCH: + """Namespace `n` holds u1's k1 and k2 (k2 at its second version), u2's k3, u2's + tombstoned k4 and an unnamed k6; namespace `other` holds a row with k2's identity.""" + db = KeptCH(tmp_path_factory.mktemp("live-revisions"), ddl("memory")) + db.create( + _memory(A1, "n", "u1", "k1"), + _memory(A2, "n", "u1", "k2"), + _memory(A2, "n", "u1", "k2", version=2), + _memory(A3, "n", "u2", "k3"), + _memory(A4, "n", "u2", "k4", tombstoned=True), + _memory(A5, "other", "u1", "k2"), + _memory(A6, "n", "u1", "k6"), + ) + return db + + +# Both branches in one statement, a list that names no row bound empty. +_JOINED = """ + SELECT toString(memory_id) AS id, version + FROM loom.memory FINAL + WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL + AND (memory_id IN {ids:Array(UUID)} + OR (agent, user_id, session_id, memory_key) + IN {identities:Array(Tuple(String, String, String, String))}) +""" + +_K2: RowKey = ("a", "u1", "s", "k2") +_K3: RowKey = ("a", "u2", "s", "k3") +_K4: RowKey = ("a", "u2", "s", "k4") +_ABSENT: RowKey = ("a", "u1", "s", "absent") + + +def _revisions(rows: list[dict[str, Any]], id_column: str) -> list[tuple[str, int]]: + return sorted((str(r[id_column]), int(r["version"])) for r in rows) + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="needs the clickhouse binary") +@pytest.mark.parametrize( + ("ids", "identities", "whole", "own_u1"), + [ + # by id: the live row of this namespace, not the tombstoned one or another's + ([A1, A3, A4, A5], [], [(A1, 1), (A3, 1)], [(A1, 1)]), + # by identity: the head version, and nothing for a key that holds no row + ([], [_K2, _K3, _K4, _ABSENT], [(A2, 2), (A3, 1)], [(A2, 2)]), + # by both: a row named by its id and by its identity is one row + ([A1, A3, A4, A5], [_K2, _K3, _K4], [(A1, 1), (A2, 2), (A3, 1)], [(A1, 1), (A2, 2)]), + ], +) +async def test_each_shape_returns_the_rows_of_the_joined_form( + memory: KeptCH, + ids: list[str], + identities: list[RowKey], + whole: list[tuple[str, int]], + own_u1: list[tuple[str, int]], +) -> None: + """A shape that drops or adds a row against the joined statement fails here, over + the whole namespace and inside one user's read scope.""" + for scope, expected in ((WHOLE_NAMESPACE, whole), (OWN_U1, own_u1)): + params: dict[str, Any] = {"org": "o", "ns": "n", "ids": ids, "identities": identities} + joined = await memory.query_all(_JOINED + scope_and(scope, params), params) + rows = await live_revisions( + "o", + "n", + scope=scope, + memory_ids=ids, + identities=identities, + hash_max_bytes=0, + ch=memory, # type: ignore[arg-type] + ) + assert _revisions(rows, "memory_id") == _revisions(joined, "id") == expected diff --git a/tests/unit/test_namespace_audit.py b/tests/unit/test_namespace_audit.py index 596bbcc7450..bc963209a89 100644 --- a/tests/unit/test_namespace_audit.py +++ b/tests/unit/test_namespace_audit.py @@ -71,7 +71,7 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None): M_EPI = "length(value) > {episodic_chars:UInt32}" M_VER = "FROM loom.memory_versions FINAL" # The one read after the checks: the live revision of every sampled row. -M_CITE = "IN {identities:Array(Tuple(String, String, String, String))}" +M_CITE = "toString(memory_id) AS id, version, sensitivity" M_VALUE = "IN {keys:Array(Tuple(String, String, String, String))}" @@ -840,7 +840,7 @@ async def test_findings_carry_the_contract_and_cite_the_live_revisions( # One citation read for the whole report, bound to the sampled rows' ids only. cites = [p for sql, p in zip(ch.sqls, ch.params, strict=True) if M_CITE in sql] assert len(cites) == 1 and cites[0]["ids"] == sorted([_mid("a"), _mid("b")]) - assert cites[0]["identities"] == [] + assert "identities" not in cites[0] # Summary reads are rules the findings depend on. assert out.coverage.complete assert out.coverage.rules_run == [*na._SUMMARY_STEPS, *na.FINDING_CODES, "evidence"] diff --git a/tests/unit/test_namespace_validate.py b/tests/unit/test_namespace_validate.py index c17ad5a9de1..8a7174d765e 100644 --- a/tests/unit/test_namespace_validate.py +++ b/tests/unit/test_namespace_validate.py @@ -354,7 +354,7 @@ async def test_findings_carry_the_contract_and_cite_the_live_revisions( "memory_id": "00000000-0000-0000-0000-0000000000ff", }, ], - "IN {identities:Array(Tuple(String, String, String, String))}": [revision], + "toString(memory_id) AS id, version, sensitivity": [revision], } ) monkeypatch.setattr(nv, "get_client", lambda: ch)