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
8 changes: 7 additions & 1 deletion docs/architecture/memory-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -1329,7 +1329,13 @@ usage fold's counters on `memory` are batched lightweight updates; see
Under the ClickHouse authority, every memory version insert holds a Keeper fence per
identity key. `memory.lock`, `memory.unlock` and `memory.verify` check that the source
row is still the head inside the fence, and answer 503 `ADMISSION_CONTENDED` with
no version written when it moved. `memory.verify` first compares `if_match_sha256`, when
no version written when it moved. `memory.update` and `memory.update_by_id` make the
same check on the head they read, with or without `if_match_sha256`, and under Postgres
their commit makes it: a revision carries every column it does not set from that head,
so over another head it would sit below a later version or overwrite what that head
changed. A refused revision writes no version row and no search document, and its
caller reads the row again to decide whether the edit still applies.
`memory.verify` first compares `if_match_sha256`, when
sent, with the hash of the head it read and answers 409 `PRECONDITION_FAILED` on
another; the fence covers a head that moves after that comparison. All value inserts
take the same fences, including
Expand Down
13 changes: 8 additions & 5 deletions docs/architecture/storage-authority.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@ the key, a write drawn later or one from a replica whose clock is ahead. A judge
supersession goes one above the version it read; its vector rows take a version the
status mirror draws (`mirror_status_to_embeddings(judged=True)`). Under the ClickHouse
authority every memory insert takes per-key Keeper fences. `memory.lock`,
`memory.unlock` and `memory.verify` compare the source rows inside those fences and
answer 503 `ADMISSION_CONTENDED` without inserting when a head has moved. Value writers
`memory.unlock`, `memory.verify`, `memory.update` and `memory.update_by_id` compare the
rows they read inside those fences and answer 503 `ADMISSION_CONTENDED` without
inserting when a head has moved. Value writers
take the same fences, so another replica cannot insert between that check and the copy.
The comparison includes the served value and persisted metadata: clock skew can make
two writers choose the same version. Derived usage fields (`recall_count`,
Expand Down Expand Up @@ -402,9 +403,11 @@ sequenceDiagram
([admission](#admission-under-concurrency));
- each written key's head is locked and rechecked against the row the write read:
never a delete, a pin, a lock, a status or a redaction the write did not see;
with `if_match_sha256` also that very version (compare-and-set), otherwise it may
carry a newer value (two unconditional writes of a key: the newer version wins,
as in ClickHouse); else the write starts over;
with `if_match_sha256`, and for every `memory.update` and `memory.update_by_id`,
also that very version (compare-and-set); any other write may find a newer value
there (two unconditional `memory.set` writes of a key: the newer version wins, as in
ClickHouse); else a `memory.set` starts over and a revision answers 503
`ADMISSION_CONTENDED`;
- the heads are upserted, the revisions and their deliveries inserted, and the
idempotency key, if any, marked `committed` with the revisions, under its lease
token.
Expand Down
46 changes: 21 additions & 25 deletions server/memory/app/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -790,24 +790,17 @@ async def _land_revision(
searchable: bool,
high: bool,
record: Callable[[], Awaitable[None]],
exact: bool,
op: str,
) -> pg_lease.PublicationPending | None:
"""Write the revision, record it (`record`: its audit row and announcement) and fence
a 'high' one. Under Postgres a committed revision whose publication failed returns its
PublicationPending, so the caller's follow-ups still run; any other failure raises.
`exact`: committed only over the very head read (`if_match_sha256`)."""
"""Write the revision over `existing`, the head it was built from, record it
(`record`: its audit row and announcement) and fence a 'high' one. A head another
write moved since the read refuses it with nothing written (503
`ADMISSION_CONTENDED`). Under Postgres a committed revision whose publication failed
returns its PublicationPending, so the caller's follow-ups still run; any other
failure raises."""
if pg.enabled():
return await _land_committed(
existing,
memory_row,
emb_rows,
policy,
ch,
high=high,
record=record,
exact=exact,
op=op,
existing, memory_row, emb_rows, policy, ch, high=high, record=record, op=op
)
await _land_inserted(
existing,
Expand Down Expand Up @@ -880,7 +873,6 @@ async def _land_committed(
*,
high: bool,
record: Callable[[], Awaitable[None]],
exact: bool,
op: str,
) -> pg_lease.PublicationPending | None:
"""Under Postgres: a commit refused before it ran raises with nothing in; a committed
Expand All @@ -892,7 +884,7 @@ def _fence() -> list[tuple[Any, int]]:
return [(identity_key(existing), int(memory_row["version"]))] if high else []

async with fenced_once_committed(_fence, op=op, ch=ch) as answer:
committed = await _commit_revision(existing, memory_row, emb_rows, policy, exact=exact)
committed = await _commit_revision(existing, memory_row, emb_rows, policy)
answer.mark_committed()
try:
return await _publish_revision(committed, emb_rows, ch)
Expand All @@ -912,10 +904,18 @@ async def _insert_revision(
) -> list[Any]:
"""On ClickHouse: the version row, its search document and, for a row no longer
searchable (`retire_vectors`), its vectors retired at its version: each one's
outcome. A refused memory insert publishes no search document."""
outcome. The version row goes in only over `existing`, the head it was built from:
every column it does not set is that head's, so over another head it would bury a
write or sit below one. A refused memory insert publishes no search document."""
import server.memory.store as memory_repo

await insert_memory_versions([memory_row], ch=ch, on_send=on_send, on_inserted=on_inserted)
await insert_memory_versions(
[memory_row],
ch=ch,
expected_heads={identity_key(memory_row): existing},
on_send=on_send,
on_inserted=on_inserted,
)
writes: list[Awaitable[Any]] = []
if emb_rows:
writes.append(memory_repo.insert_embedding_rows(emb_rows, ch=ch))
Expand All @@ -930,10 +930,9 @@ async def _commit_revision(
memory_row: dict[str, Any],
emb_rows: list[dict[str, Any]],
policy: dict[tuple[str, str], int] | None,
*,
exact: bool,
) -> pg_memory.Committed:
"""Under Postgres: the version row committed over the head the write read and the
"""Under Postgres: the version row committed over the very head the write read
(`heads_unchanged(exact=True)`, as `_insert_revision` checks it on ClickHouse) and the
policy its guard ran at, owing its document (the commit decides the old vectors'
retirement from the head it replaces). Nothing reaches ClickHouse unless it commits."""
from server.memory.app import pg_admission
Expand All @@ -946,9 +945,7 @@ async def _commit_revision(
targets=pg_memory.MEMORY_ROW | pg_memory.AUDIT_ROW | owed,
admission=pg_memory.Admission(
generations=dict(policy or {}),
recheck=pg_memory.heads_unchanged(
{identity_key(memory_row): existing}, exact=exact
),
recheck=pg_memory.heads_unchanged({identity_key(memory_row): existing}, exact=True),
),
)
except (pg_memory.AdmissionMoved, pg_memory.HeadMoved):
Expand Down Expand Up @@ -1123,7 +1120,6 @@ async def _write_revision(
conflict_result=conflict_result,
duplicate_of_id=duplicate_of_id,
),
exact=bool(input.if_match_sha256),
op=op,
)
follows: list[Follow] = []
Expand Down
82 changes: 82 additions & 0 deletions tests/integration/test_memory_metadata_contention.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,3 +125,85 @@ async def captured_head(*args, **kw):
await asyncio.gather(task, return_exceptions=True)
await first.disconnect()
await second.disconnect()


# One update and one verify a round: eight racing calls, inside both ops' rate buckets.
ROUNDS = 4


@pytest.mark.asyncio
async def test_update_racing_a_verify_is_the_head_or_is_refused(
control_plane_url, mint_test_token, ch_client
):
"""Each round sends memory.update_by_id and memory.verify for one key together, over
HTTP. Fails when an acknowledged write is not in the key's head: an update that
answered 200 under a verify's copy of the old value, or a verify that answered 200
under an update built from the head before it. A refused update leaves no version
row and no search document."""
if pg.enabled():
pytest.skip("exercises the ClickHouse authority")
import httpx

org, actor = unique_org("update-race"), "process:test-suite"
key = {"namespace": "notes", "agent": "writer", "memory_key": "deploy_window"}
token = mint_test_token(org=org, namespaces=[key["namespace"]])
landed: list[str] = []
refused: list[str] = []
async with httpx.AsyncClient(
base_url=control_plane_url, timeout=60.0, headers={"Authorization": f"Bearer {token}"}
) as http:

async def call(op: str, **body):
return await http.post(f"/v1/{op}", json={"org": org, **body})

async def update(value: str):
return await call("memory.update_by_id", memory_id=memory_id, value=value)

created = await call("memory.set", **key, memory_type="semantic", value=uuid4().hex)
assert created.status_code == 200, created.text
memory_id = created.json()["memory_id"]
head = (await call("memory.get", **key)).json()
for _ in range(ROUNDS):
# The opposite of what the head holds, so each verify has a row to write.
revoke = head["verification"] != "none"
value = uuid4().hex
updated, verified = await asyncio.gather(
update(value), call("memory.verify", memory_id=memory_id, revoke=revoke)
)
head = (await call("memory.get", **key)).json()
if updated.status_code == 200:
assert updated.json()["updated"] and head["value"] == value, (updated.text, head)
landed.append(value)
else:
assert updated.status_code == 503, updated.text
assert updated.json()["detail"]["code"] == "ADMISSION_CONTENDED", updated.text
assert head["value"] != value
refused.append(value)
if verified.status_code == 200:
assert verified.json()["changed"], verified.text
assert head["verified_by"] == ("" if revoke else actor), (verified.text, head)
else:
assert verified.status_code == 503, verified.text
assert verified.json()["detail"]["code"] == "ADMISSION_CONTENDED", verified.text
# One of the two reached the key's fence over the head both read.
assert 200 in (updated.status_code, verified.status_code)
# A write that lands shows both tables hold what an update writes.
sentinel = uuid4().hex
last = await update(sentinel)
assert last.status_code == 200 and last.json()["updated"], last.text
stored = {"select_sequential_consistency": 1}
versions = ch_client.query(
"SELECT value FROM loom.memory_versions WHERE org = {org:String}",
parameters={"org": org},
settings=stored,
).result_rows
documents = ch_client.query(
"SELECT content_excerpt FROM loom.memory_embeddings WHERE org = {org:String}",
parameters={"org": org},
settings=stored,
).result_rows
written = " ".join(str(value) for (value,) in versions)
searchable = " ".join(str(excerpt) for (excerpt,) in documents)
assert sentinel in written and sentinel in searchable
assert all(value in written for value in landed)
assert not [value for value in refused if value in written or value in searchable]
13 changes: 10 additions & 3 deletions tests/integration/test_vector_retire_race.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,8 @@ def __getattr__(self, name: str) -> Any:
("memory.update", True, "write"),
("bulk_set", False, "write"),
# the key has a memory row but no vector on the served model (written
# before a model change, say): only the sweep's fence covers it
# before a model change, say) and the sweep labels it 'high': the older
# update is refused over the relabelled head, so it writes no vector
("memory.update", False, "sensitivity_sweep"),
],
)
Expand All @@ -459,14 +460,16 @@ async def test_an_older_writes_late_vector_stays_under_a_newer_high_write(
"""An older plain write draws its version, then pauses in its embed call; a newer
write labelled 'high' commits; the older one resumes. Its vector carries its own
memory version, below the high write's fence, so search stays empty, with or
without a vector for the key before."""
without a vector for the key before. An older `memory.update` is refused instead:
it writes only over the head it read, which the high write replaced."""
import httpx

from server.auth.jwt import mint_token
from server.embedding import embedder as embedder_mod
from server.memory.api.models_bulk import MemoryBulkSetInput, _BulkSetEntry
from server.memory.api.models_crud import MemorySetInput, MemoryUpdateInput
from server.memory.app import bulk_set, update, write
from server.memory.store.pg_memory import AdmissionContendedError

ns = f"itest-{uuid.uuid4().hex[:12]}"
key = f"late_vector_{uuid.uuid4().hex[:6]}"
Expand Down Expand Up @@ -533,7 +536,11 @@ def newer_high_write() -> Any:
await newer_high_write()
assert await live_vectors() == 0
paused.gate.set()
await asyncio.wait_for(task, 30)
if older == "memory.update":
with pytest.raises(AdmissionContendedError):
await asyncio.wait_for(task, 30)
else:
await asyncio.wait_for(task, 30)

row = await ch.query_one(
"SELECT sensitivity FROM loom.memory FINAL WHERE org = {o:String}"
Expand Down
5 changes: 3 additions & 2 deletions tests/unit/test_memory_expiry.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,9 @@ def __init__(self) -> None:
async def insert(self, table: str, rows: list[dict[str, Any]], **_: Any) -> None:
self.inserts.append((table, rows))

async def query_all(self, *_: Any, **__: Any) -> list[dict[str, Any]]:
return []
async def query_all(self, sql: str, *_: Any, **__: Any) -> list[dict[str, Any]]:
# The revision goes in over the head it read: the key's head is that row.
return [row.model_dump()] if "PREWHERE (org, namespace" in sql else []

async def execute(self, *_: Any, **__: Any) -> None:
return None
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/test_memory_fence_publication.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ class LostAnswer:
async def query_all(self, *args, **kwargs):
if "FROM loom.memory_refusals" in args[0]:
return []
return []
return [source.model_dump()] # the head the revision was built from

async def insert(self, *args, **kw):
raise TimeoutError("the memory insert may have committed")
Expand Down
Loading
Loading