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
6 changes: 4 additions & 2 deletions docs/features/memory/writing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 9 additions & 9 deletions server/memory/app/proposals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
18 changes: 12 additions & 6 deletions server/memory/app/proposals_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down
20 changes: 8 additions & 12 deletions server/memory/store/conflicts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = [
Expand Down Expand Up @@ -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(
Expand Down
59 changes: 59 additions & 0 deletions tests/integration/test_read_scope_isolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
38 changes: 37 additions & 1 deletion tests/unit/test_conflicts_repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
Loading
Loading