diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index 340299544f..8a2f604a37 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -349,8 +349,10 @@ beside `agent`, the label the writing client sent. `memory_keys` (at most 500 ke together fit one 64 KiB parameter; a longer list is refused with a 422) lists only the pending proposals under those keys; `limit` still applies, and `total` and `count_only` count the matching rows. A key outside the caller's reach answers as a key with no -proposal. A `high` row lists no `content_sha256`: its hash comes with its value from -`memory.get_by_id`. +proposal. A token narrowed below the namespace (`read_scope`) gets in `conflict_with` only +the ids of rows inside its read scope, and its graded counts, `last_graded_at` and `ready` +come from the runs inside that scope alone. A `high` row lists no `content_sha256`: its +hash comes with its value from `memory.get_by_id`. `memory.proposal_decide` requires an administrator. Acceptance also requires an authenticated human whose subject, including linked aliases, differs from the proposer. diff --git a/server/memory/app/proposals.py b/server/memory/app/proposals.py index 012df2ce3d..6af18685ab 100644 --- a/server/memory/app/proposals.py +++ b/server/memory/app/proposals.py @@ -26,7 +26,7 @@ from fastapi import HTTPException -from server.identity.domain.read_scope import WHOLE_NAMESPACE +from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters, scope_and from server.memory.app import webhooks from server.memory.domain.proposal_policy import ProposalPolicy, parse_policy from server.settings import settings @@ -121,21 +121,20 @@ class GradedCounts: ARRAY JOIN memories_used AS key WHERE org = {org:String} AND namespace = {ns:String} AND grade IN ('pass', 'fail') - AND key IN {keys:Array(String)} - GROUP BY key -""" + AND key IN {keys:Array(String)}""" async def graded_counts( - ch: Any, org: str, namespace: str, keys: list[str] + ch: Any, org: str, namespace: str, keys: list[str], scope: ReadFilters ) -> dict[str, GradedCounts]: - """Graded runs that relied on each key: `memories_used` of every run with - a pass / fail grade. One statement; a run counts once per key.""" + """Graded runs inside `scope` that relied on each key: `memories_used` of every + such run with a pass / fail grade. One statement; a run counts once per key.""" wanted = sorted({k for k in keys if k}) if not wanted: return {} + params: dict[str, Any] = {"org": org, "ns": namespace, "keys": wanted} rows = await ch.query_all( - _GRADED_COUNTS_SQL, params={"org": org, "ns": namespace, "keys": wanted} + f"{_GRADED_COUNTS_SQL}{scope_and(scope, params)}\n GROUP BY key", params=params ) return { str(r["key"]): GradedCounts( @@ -358,7 +357,8 @@ async def apply_policy( proposed = await proposal_keys_among(ch, org, namespace, keys) if not proposed: return [] - counts = await graded_counts(ch, org, namespace, proposed) + # The owner's rule judges for the namespace, whatever scope the grading request reads. + counts = await graded_counts(ch, org, namespace, proposed, WHOLE_NAMESPACE) rejected = [ key for key in proposed diff --git a/server/memory/app/proposals_ops.py b/server/memory/app/proposals_ops.py index c40c6f2fd6..bdcc33c8a3 100644 --- a/server/memory/app/proposals_ops.py +++ b/server/memory/app/proposals_ops.py @@ -69,6 +69,7 @@ async def _pending_count(ch: Any, input: MemoryProposalsInput) -> int: async def handle_memory_proposals(input: MemoryProposalsInput) -> MemoryProposalsOutput: from server.memory.app import proposals as _p + from server.memory.store import conflicts as conflicts_repo # Checked here, after the namespace grant, so a caller outside it is refused first. if input.count_only and input.only: @@ -100,7 +101,8 @@ async def handle_memory_proposals(input: MemoryProposalsInput) -> MemoryProposal ) policy = await _p.policy_for(input.org, input.namespace, ch=ch) keys = [str(r["memory_key"]) for r in rows] - counts = await _p.graded_counts(ch, input.org, input.namespace, keys) + scope = request_scope() + counts = await _p.graded_counts(ch, input.org, input.namespace, keys, scope) usage = await _usage_counts(ch, input.org, input.namespace, [str(r["mid"]) for r in rows]) out: list[MemoryProposal] = [] for r in rows: @@ -133,11 +135,15 @@ async def handle_memory_proposals(input: MemoryProposalsInput) -> MemoryProposal conflict_with=[str(x) for x in (r.get("conflict_with") or []) if x], ) ) - return MemoryProposalsOutput( - proposals=out[: input.limit], - total=len(rows), - policy=policy, - ) + page = out[: input.limit] + if scope.narrowed: + # A contradicting row outside the scope is not named, not even by its id. + visible = await conflicts_repo.ids_in_scope( + ch, input.org, input.namespace, [i for p in page for i in p.conflict_with], scope + ) + for p in page: + p.conflict_with = [i for i in p.conflict_with if i in visible] + return MemoryProposalsOutput(proposals=page, total=len(rows), policy=policy) async def _usage_counts( diff --git a/server/memory/store/conflicts.py b/server/memory/store/conflicts.py index 82cda654ae..80c7da5092 100644 --- a/server/memory/store/conflicts.py +++ b/server/memory/store/conflicts.py @@ -23,7 +23,7 @@ from datetime import datetime from typing import Any -from server.core.repo_base import _CHClient, _default_client +from server.core.repo_base import _CHClient, _default_client, query_all_sliced from server.identity.domain.read_scope import ReadFilters, scope_and, scope_where from server.memory.domain.delete_marks import carried_trace @@ -76,7 +76,7 @@ async def list_conflicted( return [] if scope.narrowed: # A peer outside the scope is not named, not even by its id. - visible = await _ids_in_scope( + visible = await ids_in_scope( ch, org, namespace, [str(p) for r in located for p in r["conflict_with"]], scope ) located = [ @@ -109,24 +109,20 @@ async def list_conflicted( return out -async def _ids_in_scope( +async def ids_in_scope( ch: _CHClient, org: str, namespace: str, memory_ids: list[str], scope: ReadFilters ) -> set[str]: - """The ids among `memory_ids` whose rows lie inside `scope`.""" - if not memory_ids: - return set() + """The ids among `memory_ids` whose rows lie inside `scope`. A row's `conflict_with` + has no cap, so the ids are bound a slice at a time; no id, no statement.""" params: dict[str, Any] = {"org": org, "ns": namespace, "ids": sorted(set(memory_ids))} - rows = await ch.query_all( - f""" + sql = f""" SELECT DISTINCT toString(memory_id) AS mid FROM loom.memory WHERE org = {{org:String}} AND namespace = {{ns:String}} AND memory_id IN {{ids:Array(UUID)}}{scope_and(scope, params)} - """, - params=params, - ) - return {str(r["mid"]) for r in rows} + """ + return {str(r["mid"]) for r in await query_all_sliced(ch, sql, params, "ids")} async def count_review( diff --git a/tests/integration/test_read_scope_isolation.py b/tests/integration/test_read_scope_isolation.py index 5e1557f080..7d14499d9d 100644 --- a/tests/integration/test_read_scope_isolation.py +++ b/tests/integration/test_read_scope_isolation.py @@ -1472,3 +1472,62 @@ def keys(tok: str) -> list[str]: u_tok = _mint(seed.org, ns, read_scope="own_user", read_user_id=U) wait_until(lambda: keys(v_tok) == [key], description="V's retirement is recorded") assert keys(u_tok) == [] + + +def _record_contradictions(ch: Any, org: str, ns: str, memory_id: str, peers: list[str]) -> None: + """A newer loom.memory version of the row naming `peers` in `conflict_with`. + `memory.set` judges a write that names its user against that user's rows alone, so + the test stores the contradiction with another user's row itself.""" + ch.command( + """ + INSERT INTO loom.memory + SELECT * REPLACE ({peers:Array(UUID)} AS conflict_with, version + 1 AS version) + FROM loom.memory FINAL + WHERE org = {org:String} AND namespace = {ns:String} AND memory_id = {mid:UUID} + """, + parameters={"org": org, "ns": ns, "mid": memory_id, "peers": peers}, + ) + + +def test_a_proposal_names_no_contradiction_and_counts_no_graded_run_outside_the_scope( + control_plane_url: str, seed: _Seed, ch_client: Any +) -> None: + """U's proposal recorded a contradiction with U's fact and with V's, and one graded + run of each user relied on its key: memory.proposals under a token pinned to U names + U's fact alone and counts U's run alone.""" + ns = f"rs-prop-{uuid.uuid4().hex[:8]}" + ns_tok = _mint(seed.org, ns) + base = {"org": seed.org, "namespace": ns, "agent": "a"} + key = "deploy_window" + + def put(user: str, memory_key: str, value: str, **more: Any) -> str: + body = {**base, "user_id": user, "memory_key": memory_key, "value": value, **more} + return str(_write(control_plane_url, ns_tok, "memory.set", body)["memory_id"]) + + # The proposal first: a fact is never judged against a row on trial. + trial = put(U, key, "Deploys run on Tuesday mornings before ten", proposed=True) + u_fact = put(U, "u-fact", "Deploys run on Thursday afternoons") + v_fact = put(V, "v-fact", "Deploys run on Friday evenings") + _record_contradictions(ch_client, seed.org, ns, trial, [u_fact, v_fact]) + for user, grade in ((U, "pass"), (V, "fail")): + begun = _write( + control_plane_url, ns_tok, "run.begin", {**base, "user_id": user, "goal": "deploy"} + ) + run = {"org": seed.org, "namespace": ns, "run_id": begun["run_id"]} + _write( + control_plane_url, + ns_tok, + "run.complete", + {**run, "user_id": user, "status": "completed", "memories_used": [key]}, + ) + _write(control_plane_url, ns_tok, "run.grade", {**run, "grade": grade}) + + def listed(tok: str) -> tuple[list[str], int, int]: + out = _write(control_plane_url, tok, "memory.proposals", {"org": seed.org, "namespace": ns}) + [row] = out["proposals"] + assert row["memory_id"] == trial, row + return row["conflict_with"], row["graded_passes"], row["graded_fails"] + + # Control: a namespace-wide read names both contradictions and counts both runs. + assert listed(ns_tok) == ([u_fact, v_fact], 1, 1) + assert listed(_mint(seed.org, ns, read_scope="own_user", read_user_id=U)) == ([u_fact], 1, 0) diff --git a/tests/unit/test_conflicts_repo.py b/tests/unit/test_conflicts_repo.py index f386a2ba8b..60889bd279 100644 --- a/tests/unit/test_conflicts_repo.py +++ b/tests/unit/test_conflicts_repo.py @@ -2,17 +2,20 @@ from __future__ import annotations +import uuid from datetime import UTC, datetime from typing import Any import pytest -from server.identity.domain.read_scope import WHOLE_NAMESPACE +from server.core import ch_params +from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters from server.memory.store.conflicts import ( allowlist_exists, allowlist_insert, allowlist_list, allowlist_remove, + ids_in_scope, list_conflicted, lookup_keys_for_ids, lookup_target, @@ -61,6 +64,39 @@ async def test_list_conflicted_filters_and_paginates() -> None: assert params["limit"] == 50 +@pytest.mark.asyncio +async def test_ids_in_scope_reads_more_ids_than_one_parameter_carries() -> None: + """A page's contradicting ids have no cap, and ClickHouse refuses a parameter past + its field limit: every statement binds a slice that fits, under the same scope, and + the answer is the visible ids of all of them.""" + ids = [str(uuid.UUID(int=i)) for i in range(2000)] + assert not ch_params.fits(ids) + inside = set(ids[::2]) + + class _Scoped(StubCH): + async def query_all(self, sql, params=None): + await super().query_all(sql, params) + return [{"mid": i} for i in params["ids"] if i in inside] + + ch = _Scoped() + scope = ReadFilters(scope="own_user", user_id="u", session_id=None) + # Given twice and out of order: each id is bound once. + assert await ids_in_scope(ch, "o", "ns", [*reversed(ids), *ids], scope) == inside + sent = [params["ids"] for _, params in ch.query_all_calls] + assert len(sent) > 1 and all(ch_params.fits(part) for part in sent) + assert [i for part in sent for i in part] == ids + assert all("u" in params.values() for _, params in ch.query_all_calls) + assert len({sql for sql, _ in ch.query_all_calls}) == 1 + + +@pytest.mark.asyncio +async def test_ids_in_scope_of_no_id_sends_no_statement() -> None: + ch = StubCH() + scope = ReadFilters(scope="own_user", user_id="u", session_id=None) + assert await ids_in_scope(ch, "o", "ns", [], scope) == set() + assert ch.query_all_calls == [] + + @pytest.mark.asyncio async def test_lookup_target_returns_none_when_missing() -> None: ch = StubCH() diff --git a/tests/unit/test_proposals_read_scope.py b/tests/unit/test_proposals_read_scope.py new file mode 100644 index 0000000000..bf6ec417a5 --- /dev/null +++ b/tests/unit/test_proposals_read_scope.py @@ -0,0 +1,155 @@ +"""`memory.proposals` under a read scope below the namespace, on clickhouse-local against +the real tables: it names no contradicting row and counts no graded run outside the scope, +and the namespace's policy still judges a proposal on every run.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from server.identity.app.request_scope import request_scope +from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters +from server.memory.api.models_proposals import MemoryProposal, MemoryProposalsInput +from server.memory.app import proposals, proposals_ops +from server.memory.domain.proposal_policy import ProposalPolicy +from tests.unit.clickhouse_local import CLICKHOUSE, LocalCH, ddl +from tests.unit.principals import acting_as, principal + +pytestmark = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") + +_TRIAL, _MINE, _OTHER_SESSION, _THEIRS, _SHARED = ( + f"00000000-0000-0000-0000-00000000000{i}" for i in "abcde" +) +_OWN_USER = ReadFilters(scope="own_user", user_id="u", session_id=None) +_OWN_SESSION = ReadFilters(scope="own_session", user_id="u", session_id="s1") +_GRADED = "2026-01-02 03:04:05.000" + + +def _fact(mid: str, key: str, user: str, session: str) -> str: + return f"('o', 'n', 'a', '{user}', '{session}', '{mid}', '{key}', 'a fact', 'active', [], 1)" + + +# The proposal of user `u` in session `s1` recorded a contradiction with each fact. +_MEMORY = ( + "INSERT INTO loom.memory (org, namespace, agent, user_id, session_id, memory_id, " + "memory_key, value, status, conflict_with, version) VALUES " + f"('o', 'n', 'a', 'u', 's1', '{_TRIAL}', 'trial', 'a fact on trial', 'proposed', " + f"{[_MINE, _OTHER_SESSION, _THEIRS, _SHARED]}, 1), " + + ", ".join( + [ + _fact(_MINE, "mine", "u", "s1"), + _fact(_OTHER_SESSION, "other_session", "u", "s2"), + _fact(_THEIRS, "theirs", "v", "s1"), + _fact(_SHARED, "shared", "-", "-"), + ] + ) +) + + +def _run(run_id: str, user: str, session: str, grade: str) -> str: + return ( + f"('o', 'n', 'a', '{user}', '{session}', '{run_id}', 'completed', ['trial'], " + f"'{grade}', '{_GRADED}', 1)" + ) + + +def _runs(*rows: str) -> str: + return ( + "INSERT INTO loom.agent_runs (org, namespace, agent, user_id, session_id, run_id, " + "status, memories_used, grade, graded_at, version) VALUES " + ", ".join(rows) + ) + + +# One pass in the caller's session, one in the caller's other session, and two fails +# by runs outside the scope of user `u`: another user's and one of no user. +_RUNS = _runs( + _run("r1", "u", "s1", "pass"), + _run("r2", "u", "s2", "pass"), + _run("r3", "v", "s1", "fail"), + _run("r4", "-", "-", "fail"), +) + + +@pytest.fixture +def trial(monkeypatch: pytest.MonkeyPatch) -> Any: + """The handler's answer for the one proposal under `scope`, read from the real + statements; the policy and the usage counters beside them are answered empty.""" + + async def _policy(*_a: Any, **_k: Any) -> ProposalPolicy: + return ProposalPolicy() + + async def _empty(*_a: Any, **_k: Any) -> dict[str, Any]: + return {} + + ch = LocalCH(ddl("memory"), ddl("agent_runs"), _MEMORY, _RUNS) + monkeypatch.setattr(proposals, "policy_for", _policy) + monkeypatch.setattr(proposals_ops, "_usage_counts", _empty) + monkeypatch.setattr(proposals_ops, "get_client", lambda: ch) + + async def read(scope: ReadFilters) -> MemoryProposal: + monkeypatch.setattr(proposals_ops, "request_scope", lambda: scope) + out = await proposals_ops.handle_memory_proposals( + MemoryProposalsInput(org="o", namespace="n") + ) + [proposal] = out.proposals + assert proposal.memory_key == "trial" + return proposal + + return read + + +async def test_a_contradiction_outside_a_narrowed_scope_is_not_named(trial: Any) -> None: + # Another user's row and a row of no user are outside the scope of user `u`. + assert (await trial(_OWN_USER)).conflict_with == [_MINE, _OTHER_SESSION] + # Under `own_session` the caller's own row in another session is outside it too. + assert (await trial(_OWN_SESSION)).conflict_with == [_MINE] + + +async def test_a_whole_namespace_reader_sees_every_recorded_contradiction(trial: Any) -> None: + assert (await trial(WHOLE_NAMESPACE)).conflict_with == [ + _MINE, + _OTHER_SESSION, + _THEIRS, + _SHARED, + ] + + +async def test_graded_runs_outside_a_narrowed_scope_are_not_counted(trial: Any) -> None: + def counted(p: MemoryProposal) -> tuple[int, int, str]: + return p.graded_passes, p.graded_fails, p.ready + + # The two fails are outside the scope, so the caller's two passes read as `accept`. + assert counted(await trial(_OWN_USER)) == (2, 0, "accept") + # One pass is in the caller's other session: one short of the default `min_passes`. + assert counted(await trial(_OWN_SESSION)) == (1, 0, "") + # Control: the same runs, read by the whole namespace, hold the proposal back. + assert counted(await trial(WHOLE_NAMESPACE)) == (2, 2, "") + + +async def test_the_policy_counts_the_whole_namespace(monkeypatch: pytest.MonkeyPatch) -> None: + """Two users' runs each failed the proposal once. `reject_after_fails=2` rejects it, + also from a grading request bound to one of the two users.""" + + async def _policy(*_a: Any, **_k: Any) -> ProposalPolicy: + return ProposalPolicy(mode="auto", reject_after_fails=2) + + async def _proposed(*_a: Any, **_k: Any) -> list[str]: + return ["trial"] + + async def _decide(_org: str, _ns: str, keys: list[str], decision: str, **_k: Any) -> Any: + assert decision == "reject" + return [proposals.DecideResult(key, True, "rejected") for key in keys] + + monkeypatch.setattr(proposals, "policy_for", _policy) + monkeypatch.setattr(proposals, "proposal_keys_among", _proposed) + monkeypatch.setattr(proposals, "decide", _decide) + ch = LocalCH( + ddl("agent_runs"), _runs(_run("r1", "u", "s1", "fail"), _run("r2", "v", "s1", "fail")) + ) + with acting_as(principal("admin", org="o", namespaces=("n",), read_user_id="u")): + assert request_scope() == _OWN_USER + decided = await proposals.apply_policy("o", "n", ["trial"], ch=ch) + assert decided == [ + ("trial", "reject", proposals.GradedCounts(passes=0, fails=2, last_graded_at=_GRADED)) + ]