From 967ab8b3b327e413d51e1d0d433f98de5737ec87 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sat, 5 Dec 2026 00:27:56 +0000 Subject: [PATCH] A write with proposed=true waits for review whatever its type or sensitivity memory.set takes its plain insert for a type that is not embedded (episodic, profile) and for a value the sensitivity gate reads as high. That path returned before the lifecycle stamp, so such a proposal was stored active with requires_review = 0 and served with no review. _stamp_lifecycle runs before the plain insert as it does before the dual write, and the write answers status "proposed". The profile leg of loom_search reads served sections only, as profile.render does: a section that is proposed, rejected or retired is no hit and gets no re-embed stub. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/memory-architecture.md | 11 +- .../memory/working-memory-and-profiles.md | 3 +- docs/features/memory/writing.md | 7 +- server/memory/app/profile_search.py | 13 +- server/memory/app/set_commit.py | 2 + server/memory/app/write.py | 8 +- tests/integration/test_proposals.py | 86 +++++++++ tests/unit/test_memory_set_proposed.py | 172 ++++++++++++++++++ 8 files changed, 287 insertions(+), 15 deletions(-) create mode 100644 tests/integration/test_proposals.py create mode 100644 tests/unit/test_memory_set_proposed.py diff --git a/docs/architecture/memory-architecture.md b/docs/architecture/memory-architecture.md index 4652aa52eb5..f888987ec58 100644 --- a/docs/architecture/memory-architecture.md +++ b/docs/architecture/memory-architecture.md @@ -107,10 +107,13 @@ outcome (refusal, 4xx `rejected`, or `error`) and to attach value-shape advisori 8. **Non-embedded rows stop here.** A type in `NON_SEARCHABLE_TYPES` (`episodic`, `profile`) or a `high`-sensitivity row gets one insert and no embedding row (`server/memory/domain/memory_types.py`, `is_embedded`). No embedding row means no search leg sees - it. A successful ClickHouse insert requires the same acknowledged hash-only audit - receipt as an embedded insert. Receipt failure returns `BACKEND_UNAVAILABLE` after - the committed row's safety follow-ups finish; the memory remains written. Under - Postgres, the commit already includes the revision audit row. + it. A `proposed=true` row is stamped `proposed` with `requires_review` before this + insert (`_stamp_lifecycle`), as an embedded row is before its dual write, so a proposal + of any type or sensitivity waits for review. A successful ClickHouse insert requires + the same acknowledged hash-only audit receipt as an embedded insert. Receipt failure + returns `BACKEND_UNAVAILABLE` after the committed row's safety follow-ups finish; the + memory remains written. Under Postgres, the commit already includes the revision audit + row. 9. **Embed** (`_set_embed`) the value and, when the key carries words, the key, in one batched call where the embedder supports it. 10. **Conflict verdict** (`_set_conflict_verdict`, `memory/app/conflicts.py` diff --git a/docs/features/memory/working-memory-and-profiles.md b/docs/features/memory/working-memory-and-profiles.md index 35ac6ba4edf..1fa24138b77 100644 --- a/docs/features/memory/working-memory-and-profiles.md +++ b/docs/features/memory/working-memory-and-profiles.md @@ -90,7 +90,8 @@ Field lists: [operations reference](../../reference/operations.md#profile). (`user_id` `-`) render. - **Search.** Profile rows stay out of `memory.search`. The `loom_search` tool has a profile leg that scores sections by meaning when a question is about the user; each - section's vector is refreshed off the request path after every write. See + section's vector is refreshed off the request path after every write. A section that + is proposed, rejected or retired is no hit, as it is no part of the render. See [unified search](../unified-search.md). - **Folding facts into a profile.** The `profile_consolidation` worker (off by default, `LOOM_PROFILE_CONSOLIDATION_ENABLED`) folds a user's preference and decision memories diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index b4e1cdd54db..8e184a748a1 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -334,8 +334,11 @@ listed on no MCP toolset: an MCP client calls `loom_memory_import` by name. Fiel `memory.set(proposed=true)` writes a fact on trial (`status='proposed'`). It is served only to reads that pass `include_proposed`, and never retires, supersedes or flags an established -fact. The `relations` it names stay out of the fact graph, and accepting it does not add -them: state them again once it is established. A key that already holds a fact answers 409 +fact. A proposal waits for review whatever its type or sensitivity: an `episodic` or +`profile` row and a `high` value are stored `proposed` too, and stay out of the profile +render, the context pack and every search until they are accepted. The `relations` a +proposal names stay out of the fact graph, and accepting it does not add them: state them +again once it is established. A key that already holds a fact answers 409 `KEY_HOLDS_FACT`. `memory.proposals` lists proposals with the graded runs that relied on each. A run in the proposal's namespace counts toward its trial when it names the key in `run.complete(memories_used=…)` and is graded with `run.grade`. Pass thresholds mark a diff --git a/server/memory/app/profile_search.py b/server/memory/app/profile_search.py index de35eedf1fe..8a61e4583de 100644 --- a/server/memory/app/profile_search.py +++ b/server/memory/app/profile_search.py @@ -35,6 +35,7 @@ from typing import Any from server.identity.domain.read_scope import ReadFilters, scope_and +from server.memory.domain.temporal_sql import served_status_sql from server.observability import degradations from server.settings import settings @@ -54,16 +55,18 @@ # Step 2: the live rows of exactly those keys. The key tuple is the sort key, # so PREWHERE is safe under FINAL: every version of a key -# shares it. memory_type and tombstoned_at are not key columns, so they stay in -# WHERE, after the merge. -PROFILE_FETCH_SQL = """ +# shares it. memory_type, tombstoned_at and status are not key columns, so they +# stay in WHERE, after the merge. +PROFILE_FETCH_SQL = f""" SELECT namespace, agent, user_id, session_id, memory_key, value, created_at, cityHash64(concat(memory_key, '\\n', value)) AS text_hash FROM loom.memory FINAL -PREWHERE org = {org:String} +PREWHERE org = {{org:String}} AND (namespace, agent, user_id, session_id, memory_key) - IN {keys:Array(Tuple(String, String, String, String, String))} + IN {{keys:Array(Tuple(String, String, String, String, String))}} WHERE memory_type = 'profile' AND tombstoned_at IS NULL + -- a section that is proposed, rejected or retired is no hit and gets no stub + AND {served_status_sql()} -- a head scrubbed by memory.redact is no section to find AND redacted_at IS NULL -- a 'high' section is never embedded or ranked: no stub, no vector, no hit diff --git a/server/memory/app/set_commit.py b/server/memory/app/set_commit.py index 970ee3aaa65..7b53b9be76f 100644 --- a/server/memory/app/set_commit.py +++ b/server/memory/app/set_commit.py @@ -624,6 +624,8 @@ async def _set_plain_insert(w: _SetWrite, ch: Any) -> MemorySetOutput: namespace=input.namespace, memory_key=input.memory_key, degraded=_degradations.current(), + # No verdict to report; a proposal's writer still reads that its row waits for review. + status="proposed" if memory_row.get("status") == "proposed" else "", ) diff --git a/server/memory/app/write.py b/server/memory/app/write.py index 9345e70c80f..c196414e7bd 100644 --- a/server/memory/app/write.py +++ b/server/memory/app/write.py @@ -741,6 +741,7 @@ async def _memory_set_once(input: MemorySetInput, *, embedder: Any = None) -> Me # Non-searchable type, or a 'high' sensitivity row: single insert is the # only work — no embedding row means no search leg can return it. if not is_embedded(w.input.memory_type, w.effective_sensitivity): + _stamp_lifecycle(w.memory_row, None, w.input) return await finished(w, _set_plain_insert(w, ch)) # Searchable: prepare the embedding too, validating its width before calling @@ -802,10 +803,11 @@ async def _memory_set_once(input: MemorySetInput, *, embedder: Any = None) -> Me def _stamp_lifecycle( memory_row: dict[str, Any], conflict_result: Any, input: MemorySetInput ) -> str: - """The row's lifecycle status before insert; returns `duplicate_of`. + """The row's lifecycle status before either insert; returns `duplicate_of`. A duplicate verdict (the canonical already holds the fact) wins over - `proposed` (a fact on trial).""" - if conflict_result.verdict == "duplicate": + `proposed` (a fact on trial). The plain insert checks no peer and passes no + verdict: its proposal waits for review like any other.""" + if conflict_result is not None and conflict_result.verdict == "duplicate": dup = conflict_result.duplicate_of_id or "" memory_row["status"], memory_row["duplicate_of"] = "duplicate", dup return dup diff --git a/tests/integration/test_proposals.py b/tests/integration/test_proposals.py new file mode 100644 index 00000000000..302c1fbe3a7 --- /dev/null +++ b/tests/integration/test_proposals.py @@ -0,0 +1,86 @@ +"""A proposal of a type that is not embedded waits for review and is accepted from it.""" + +from __future__ import annotations + +from typing import Any + +import httpx +import pytest + +from server.auth.jwt import mint_token +from tests.integration._resources import unique_org + + +@pytest.mark.asyncio +async def test_a_profile_proposal_is_accepted_from_its_review(control_plane_url: str) -> None: + """A `profile` proposal is stored pending and kept out of the rendered profile; the + review lists it, and an accept with the listed hash makes it the served section.""" + org, ns = unique_org("proposal-profile"), "people" + scope = {"org": org, "namespace": ns} + identity = {**scope, "agent": "author", "memory_key": "drinks"} + value = "Prefers oolong tea in the afternoon" + + def token(subject: str, *, human: bool, role: str) -> str: + return mint_token( + subject=subject, + org=org, + namespaces=[ns], + roles=[role], + ttl_seconds=600, + is_service_account=not human, + ) + + author = token("proposer", human=False, role="writer") + reviewer = token("reviewer", human=True, role="admin") + + async with httpx.AsyncClient(base_url=control_plane_url, timeout=120) as client: + + async def call(op: str, body: dict[str, Any], bearer: str) -> dict[str, Any]: + r = await client.post( + f"/v1/{op}", json=body, headers={"Authorization": f"Bearer {bearer}"} + ) + assert r.status_code == 200, f"{op}: {r.status_code} {r.text[:400]}" + return r.json() + + async def pending() -> list[dict[str, Any]]: + return (await call("memory.proposals", scope, reviewer))["proposals"] + + async def rendered() -> list[str]: + return (await call("profile.render", {**scope, "agent": "author"}, author))["labels"] + + wrote = await call( + "memory.set", + {**identity, "value": value, "memory_type": "profile", "proposed": True}, + author, + ) + assert wrote["status"] == "proposed", wrote + + [listed] = await pending() + assert (listed["memory_key"], listed["memory_type"]) == ("drinks", "profile") + assert listed["memory_id"] == wrote["memory_id"] + assert listed["content_sha256"] == wrote["content_sha256"] + assert await rendered() == [] + + decided = await call( + "memory.proposal_decide", + { + **scope, + "memory_keys": ["drinks"], + "decision": "accept", + "approved_sha256": {"drinks": listed["content_sha256"]}, + }, + reviewer, + ) + assert decided["decided"] == 1, decided + assert decided["results"] == [ + {"memory_key": "drinks", "decided": True, "status": "active", "reason": ""} + ] + + assert await pending() == [] + got = await call("memory.get", identity, author) + assert got["found"] is True + assert (got["status"], got["memory_type"], got["value"]) == ("active", "profile", value) + assert got["memory_id"] == wrote["memory_id"] + assert got["content_sha256"] == wrote["content_sha256"] + assert got["verified_by"] == "human:reviewer" + assert await rendered() == ["drinks"] diff --git a/tests/unit/test_memory_set_proposed.py b/tests/unit/test_memory_set_proposed.py new file mode 100644 index 00000000000..eaa30b5dc68 --- /dev/null +++ b/tests/unit/test_memory_set_proposed.py @@ -0,0 +1,172 @@ +"""`memory.set(proposed=true)` waits for review whatever the row's type or sensitivity. + +A type that is not embedded (`episodic`, `profile`) and a value the sensitivity gate +reads as `high` take the write's plain path, which checks no peer. The row it stores is +pending review like any other proposal: `memory.proposals` lists it, and the search's +profile leg and a context pack's profile and startup recall leave it out. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest + +from server.core.background import drain_task_sets +from server.identity.domain.read_scope import WHOLE_NAMESPACE +from server.memory.api.models_crud import MemorySetInput +from server.memory.app import write as write_mod +from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl +from tests.unit.memory_store import MemoryStore, wire_memory_store + +IDENTITY = {"org": "o", "namespace": "n", "agent": "a", "user_id": "u1", "session_id": "s1"} +# The gate reads a PIN as `high` with no level declared. +HIGH_VALUE = "The door PIN is 4821" + + +@pytest.fixture +def store(monkeypatch: pytest.MonkeyPatch) -> MemoryStore: + store = MemoryStore() + wire_memory_store(monkeypatch, store) + return store + + +@pytest.fixture +def announced(monkeypatch: pytest.MonkeyPatch) -> list[str]: + """The webhook events the writes announce, in order.""" + events: list[str] = [] + + async def announce(changes: Any, **_: Any) -> bool: + events.extend(event for event, _row in changes) + return False + + monkeypatch.setattr("server.memory.app.webhooks.announce", announce) + return events + + +async def _set(key: str, value: str, **fields: Any) -> Any: + return await write_mod.handle_memory_set( + MemorySetInput(**IDENTITY, memory_key=key, value=value, classify=False, **fields) + ) + + +def _live_vectors(store: MemoryStore) -> list[dict[str, Any]]: + """The vector rows a search could read: a `high` write stores a tombstoned one.""" + return [e for e in store.embeddings if e["tombstoned_at"] is None] + + +@pytest.mark.parametrize("memory_type", ["episodic", "profile"]) +async def test_a_proposed_write_of_a_non_embedded_type_lands_proposed( + store: MemoryStore, announced: list[str], memory_type: str +) -> None: + """Fails when an `episodic` or `profile` proposal is stored `active`, or announced + to webhooks as a written fact.""" + out = await _set("drinks", "likes oolong tea", memory_type=memory_type, proposed=True) + head = store.head(memory_key="drinks", agent="a") + assert head is not None and head["memory_type"] == memory_type + assert (head["status"], head["requires_review"]) == ("proposed", 1) + assert out.status == "proposed" + assert _live_vectors(store) == [] and announced == [] + + +@pytest.mark.parametrize( + ("value", "declared"), + [("an unremarkable fact", "high"), (HIGH_VALUE, "")], + ids=["declared", "detected"], +) +async def test_a_proposed_write_of_a_high_value_lands_proposed( + store: MemoryStore, announced: list[str], value: str, declared: str +) -> None: + """Fails when a `high` proposal is stored `active` or without `requires_review`, or + announced to webhooks as a written fact.""" + out = await _set("door", value, sensitivity=declared, proposed=True) + head = store.head(memory_key="door", agent="a") + assert head is not None and head["sensitivity"] == "high" + assert (head["status"], head["requires_review"]) == ("proposed", 1) + assert out.status == "proposed" + assert _live_vectors(store) == [] and announced == [] + + +@pytest.mark.parametrize( + "fields", [{"memory_type": "episodic"}, {"memory_type": "profile"}, {"sensitivity": "high"}] +) +async def test_a_plain_write_that_is_not_a_proposal_lands_active( + store: MemoryStore, announced: list[str], fields: dict[str, str] +) -> None: + """Fails when a plain write that sent no `proposed` is stored pending, answers a + status or is not announced.""" + out = await _set("drinks", "likes oolong tea", **fields) + head = store.head(memory_key="drinks", agent="a") + assert head is not None + assert (head["status"], head["requires_review"]) == ("active", 0) + assert out.status == "" and announced == ["memory.written"] + + +async def _written_rows(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: + """The rows `memory.set` stores for three proposals that take the plain path and, + beside each kind a read below serves, one write that is no proposal.""" + with monkeypatch.context() as patched: + store = MemoryStore() + wire_memory_store(patched, store) + await _set("drinks", "likes oolong tea", memory_type="profile", proposed=True) + await _set("standup", "standup moves to ten", memory_type="episodic", proposed=True) + await _set("door", HIGH_VALUE, proposed=True) + await _set("food", "likes oolong dumplings", memory_type="profile") + await _set("retro", "retro stays on friday", memory_type="episodic") + # What a first write leaves running beside its answer finishes on this store. + assert await drain_task_sets(timeout_s=5) + return [dict(r) for r in store.versions] + + +@pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") +async def test_such_a_proposal_is_listed_and_not_served( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Fails when `memory.proposals` omits such a proposal, or the search's profile leg + or a context pack's profile or startup recall serves it. The statements run on the + stored rows, and each serving read returns the write that is no proposal, so a read + that returned nothing at all fails too.""" + from server.memory.api.models_context import ContextPackInput + from server.memory.api.models_proposals import MemoryProposalsInput + from server.memory.app.context_pack import handle_context_pack + from server.memory.app.loom_search.fanout import profile_hit_matches + from server.memory.app.profile_search import search_profile + from server.memory.app.proposals_ops import handle_memory_proposals + from server.settings import settings + + ch = KeptCH( + tmp_path, + ddl("memory"), + ddl("namespaces"), + ddl("agent_runs"), + ddl("memory_usage_totals"), + ) + await ch.insert("loom.memory", await _written_rows(monkeypatch)) + monkeypatch.setattr("server.core.ch._ch", ch) + # The word rule alone: no vector is stored for a profile section here. + monkeypatch.setattr(settings, "mcp_loom_search_profile_min_similarity", 0.0) + + listed = await handle_memory_proposals(MemoryProposalsInput(org="o", namespace="n")) + by_key = {p.memory_key: p for p in listed.proposals} + assert sorted(by_key) == ["door", "drinks", "standup"] + assert by_key["drinks"].value_preview == '"likes oolong tea"' + assert (by_key["door"].sensitivity, by_key["door"].value_preview) == ("high", "") + + hits = await search_profile( + "o", ["n"], "oolong", top_k=10, lexical=profile_hit_matches, scope=WHOLE_NAMESPACE, ch=ch + ) + assert [h["label"] for h in hits] == ["food"] + + pack = await handle_context_pack( + ContextPackInput( + **IDENTITY, + mode="startup", + read_scope="own_session", + only_sections=["profile", "memories"], + ) + ) + assert "oolong dumplings" in pack.sections["profile"] + assert "retro stays on friday" in pack.sections["memories"] + for withheld in ("oolong tea", "standup moves to ten", "4821"): + assert withheld not in pack.rendered