Skip to content

An update that raced another write of its key answers 503 ADMISSION_CONTENDED instead of being buried - #2205

Merged
zlareb1 merged 3 commits into
mainfrom
fix/update-checks-the-head-it-read
Dec 5, 2026
Merged

zlareb1 merged 3 commits into
mainfrom
fix/update-checks-the-head-it-read

Conversation

@zlareb1

@zlareb1 zlareb1 commented Dec 5, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in a release)

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

memory.update and memory.update_by_id no longer lose a write when another write of the same key lands while they run. The update answers 503 ADMISSION_CONTENDED and writes nothing, where it answered 200 and either sat below the other write or replaced it.

Why

No issue is filed for this; the defect is described here.

memory.update and memory.update_by_id build a revision from the head they read (_write_revision in server/memory/app/update.py). Every column the request does not set is copied from that head, and the version is drawn above it (version_over(existing)) before the blacklist guard, the embedding call and the conflict check are awaited. _insert_revision then called insert_memory_versions with no expected_heads: the insert took the key's Keeper fence, read the head inside it and compared it with nothing.

Two orders lose a write that was answered 200. memory.verify is the other write in both; a memory.set, a lock or a sensitivity relabel of the key between the update's read and its insert does the same.

Order On main
The update reads head H and draws its version. memory.verify reads H, draws a later version and inserts its copy of H with the attestation. The update inserts. Both answer 200. The update's row is below the attested copy: the key serves the old value, and the update's new_version is never the head.
memory.verify reads H and draws its version. The update reads H and draws a later version. The verify inserts, then the update. Both answer 200. The update's row carries H's verification columns: the attestation the verify reported is gone.

Fifteen rounds of one memory.update_by_id and one memory.verify sent together over HTTP for one key, against a server started from source:

Build Rounds where both answered 200 Answered 200 and not in the head Refused with 503
main 14 9 updates, 5 attestations 1 verify
this branch 0 0 15 updates

The fix is one argument: _insert_revision passes expected_heads={identity_key(memory_row): existing}. checked_write (server/memory/store/write_fence.py) reads the key's head inside the fence for every memory insert. Given an expected head it compares the two (memory_head_state: the served value and the persisted metadata, without the usage counters) and raises AdmissionContendedError before the insert. _land_inserted writes the search document, the audit row and the announcement only after the memory insert returned, so a refused revision writes none of them.

  • The check applies with or without if_match_sha256. The hash says which content the caller read; the head check says which row the server built the revision from. A conditional update reads the head again under the key's write lock and passes that head.
  • Under the Postgres authority _commit_revision rechecks with heads_unchanged(exact=True). It passed exact=bool(input.if_match_sha256), so an update without a hash was committed over any head whose protection was unchanged (delete, pin, lock, status, redaction), whatever its value or attestation. The head upsert keeps the higher version, so the same two orders lost a write there. HeadMoved already maps to AdmissionContendedError.
  • The exact parameter of _land_revision, _land_committed and _commit_revision is removed: every caller passes the head it read.

Alternatives and their cost:

Alternative Cost
Read the head again inside the handler and rebuild the revision The guard, the embedding and the conflict check run again, and an update sent without a hash is applied over content its caller did not read.
Draw the version at the insert The row sits above the other write and still carries the columns of the head it read: it replaces the attestation, the lock or the relabel.

Scope and risk

One argument to one insert and one argument to one Postgres recheck. No statement, table, migration, op, field, setting or worker is added. The head read under the fence is the one every memory insert makes on main, so an idle update sends the same statements; a unit test pins them.

What a caller sees: an update whose key was written between its read and its insert answers 503 ADMISSION_CONTENDED with Retry-After: 1, where it answered 200. The served detail differs by op, read from a server on this branch:

Op Declared idempotent Served retryable SDK
memory.update_by_id yes true The Python, TypeScript, Ruby and Rust SDKs resend it within their retry budget. The resend reads the head again and builds the revision from it.
memory.update no false Not resent. The transport serves any 5xx of an op that is not idempotent with retryable: false (handler_failure_detail). The caller reads the row and sends the update again, as for memory.lock.
  • The SDKs keep no list of codes to retry. They resend by status and by the op's idempotency (_op_is_idempotent in sdk/python/loom/transport.py, the same rule in the TypeScript, Ruby and Rust transports), so no SDK file changes. The Go, Java and .NET SDKs expose the served retryable.
  • Dashboard: no control sends memory.update or memory.update_by_id. The memory drawer saves an edit with memory.set, and server/operations/dashboard.py lists both ops as not in the dashboard. No dashboard control reaches this refusal.
  • Two callers inside the server use the same write:
    • The rename follower (revise_as_pipeline, called from server/memory/app/code_renames.py). A 503 is not one of the refusals it treats as final, so the memory stays due and the next pass revises it.
    • Decision extraction's tag update (_set_tags in server/memory/app/decision_extract.py). It reports the refusal for that row (_REPORTED_ERRORS holds LoomServerError), and the next run reads the row again.
  • Concurrency: the comparison runs inside the per-key fence every memory insert takes, so no write lands between the comparison and the insert. Two updates of one key sent together: one lands and the other is refused, where both answered 200 and the lower version was buried.
  • Tenant isolation, authorization, audit shape and stored data are unchanged.
  • The op summaries and the generated reference pages are unchanged. docs/reference/errors.md lists no ops per code.

Other writers that insert a memory version without an expected head, from a walk of every call of insert_memory_versions and insert_versions_over_heads under server/:

Writer Head check on ClickHouse In this change
memory.update, memory.update_by_id, the rename follower (_insert_revision) yes added here
memory.verify, memory.lock, memory.unlock, the source redirect of memory.move, proposals.decide, expiry (_over_unmoved_heads), _tombstone_ch_heads, _write_tombstone_row with a hash or a refused value yes, on main untouched
memory.unpin, memory.touch, memory.apply (label, demote), memory.restore, namespace rollback, observe.crystallize, the observation distiller, the canonical row of memory.consolidate, the sensitivity sweep's relabel, apply_entities_batch, clear_duplicate_tag, write_versions_by_ids, _reject_heads, _write_dependents no left alone
memory.set and memory.pin (set_commit), memory.bulk_set, observe.record, memory.cross_promote, memory.copy_to, _write_above, lift_after_insert, insert_version_rows, insert_documented_versions, the import command no left alone
The Postgres publication paths (publish_rows, send_rows) not applicable: the rows are committed in Postgres untouched
  • The third row is another funnel, insert_versions_over_heads, where exact is each caller's choice. Its documented default is a copy drawn before the read, which yields to a write made since; under Postgres every one of them is exact already. Making one exact on ClickHouse gives its caller a refusal to act on: an op gains a 503 answer and its documentation, a background pass a skip and a later retry. Each is its own change with its own tests.
  • The fourth row writes the request's row. memory.set has a documented rule (two unconditional writes of a key: the newer version wins). The others were listed and not examined further.

Not in this change: how long a contended write waits before it refuses, the answer of an insert refused after its key was fenced, and anything in memory.verify.

Open pull request on the same file, another concern: #2064 changes an import and _check_update_precondition in server/memory/app/update.py, and no function this diff changes.

Compatibility, rollout and rollback

  • Wire: no op, field, table or setting is added, changed or removed, and no default changes. memory.update and memory.update_by_id answer 503 ADMISSION_CONTENDED for a head that moved during the call. Under Postgres both ops answered that code on main: with if_match_sha256 for any moved head, and without it for a head whose protection moved. On ClickHouse the code is a new answer of the two ops.
  • Operator steps: none.
  • Rolling upgrade: a replica one build behind inserts a revision without the check. While both builds serve, an update served by the older replica can still be buried or bury a write, as on main. An update served by the newer replica is checked against whatever either build wrote. No gate is added, and the window closes when the upgrade completes.
  • Rollback: reverting leaves nothing behind.

Tests

Run on this branch against a ClickHouse and a server started for it. The new tests were written and run on unchanged main before update.py was edited.

New tests:

  • tests/unit/test_memory_metadata_contention.py, three tests, each under both authorities.
    • test_update_is_refused_when_a_verify_lands_between_its_read_and_its_insert: failed on main under both authorities with DID NOT RAISE AdmissionContendedError (2 failed, 4 passed for the three tests). It holds the refusal, no version row from the update, no search document, and the fence released.
    • test_verify_is_refused_when_an_update_lands_between_its_read_and_its_insert: the other order. It passes on main, where the verify already compared heads.
    • test_update_of_an_idle_key_compares_the_head_once_and_lands: on ClickHouse the update sends, under the fence, one head read and its insert, on main and here; under Postgres the commit rechecks the head once.
    • The unit suite has no Postgres server. The Postgres cases run the handler, _commit_revision and heads_unchanged against a stand-in for pg_publish.commit that calls the recheck on the key's head, as commit_versions does under the row lock.
  • tests/integration/test_memory_metadata_contention.py::test_update_racing_a_verify_is_the_head_or_is_refused: four rounds of memory.update_by_id and memory.verify sent together over HTTP. Each 200 must be in the head, each refusal must be 503 ADMISSION_CONTENDED, one of the two lands every round, and no refused value is in loom.memory_versions or loom.memory_embeddings. Against a server running main's update.py it fails: a verify answered 200 with changed and the head held no attestation. It skips under the Postgres authority, as the file's other test does.

Existing tests changed, assertions kept:

  • Five unit tests had a fake store whose head read inside the fence returned no row, or another row than the update read. Each serves the head the update read: test_memory_write_path_mirror.py::test_update_by_id_clears_a_redaction_only_with_a_new_value (two cases), test_memory_expiry.py::test_update_by_id_refuses_an_expired_row_unless_revived, test_memory_update_by_key.py::test_a_conditional_revision_audits_the_head_it_wrote_from and test_memory_fence_publication.py::test_unanswered_high_memory_send_still_fences_search.
  • tests/unit/test_pg_authority.py: the removed exact argument is dropped from six calls.
  • tests/integration/test_vector_retire_race.py::test_an_older_writes_late_vector_stays_under_a_newer_high_write: in its two memory.update cases an older update resumes after a newer write of its key. It wrote a row below the newer one; it is refused. The test expects the refusal in those two cases and keeps every assertion on the result: the key is high, it has no live vector, and search does not return it.

Runs:

Command Result
pytest -q -n 2 over the 37 unit test files that reach the update handlers 1929 passed, 2 skipped
pytest -q -n 2 over the seven unit test files changed here or nearest the change (test_memory_metadata_contention.py, test_pg_authority.py, test_memory_update_by_key.py, test_memory_expiry.py, test_memory_fence_publication.py, test_memory_write_path_mirror.py, test_memory_verify.py) 596 passed
pytest -q -n 2 tests/unit/test_package_contracts.py tests/unit/test_op_transport_contract.py tests/unit/test_tunable_constants.py tests/unit/test_store_names_refused.py tests/unit/test_degraded_unnoted.py tests/unit/test_public_copy.py tests/unit/test_doc_links.py tests/unit/test_agent_instructions.py tests/analyzer 601 passed, 12 skipped; tests/analyzer alone: 12 passed
pytest -q -n 2 tests/integration/test_memory_metadata_contention.py tests/integration/test_vector_retire_race.py 44 passed
pytest -q -n 2 over tests/integration/test_memory_by_id.py, test_memory_precondition.py, test_memory_verify.py, test_memory_expiry.py, test_memory_lock.py, test_identity_sentinels.py and test_memory_metadata_contention.py 39 passed
pytest -q -n 2 tests/integration/same_key/test_retirement_ch.py tests/integration/test_restored_memory_ids.py tests/integration/test_memory_conflicts.py 47 passed
pytest -q -n 2 tests/integration/same_key tests/integration/test_conflict_resolver_ch.py -k "update or revis" 90 passed
pytest -q -n 2 tests/integration/test_memory_code_links.py -k "update or revis or rename or rewrit" 81 passed
make typecheck pass
ruff format --check and ruff check on the changed files; ruff check server extractor sdk/python tests scripts .claude; the function-length and secret gates; Prettier on the two changed pages clean

The rows above ran on the branch's own commit. The branch then merged main, which changed docs/architecture/storage-authority.md beside this diff's paragraphs, without a conflict. On the merged head:

Command Result
make typecheck pass
pytest -q -n 2 over the seven unit files above, test_decision_extract.py, test_memory_code_rename_plan.py, the eight repository scans and tests/analyzer 1798 passed, 12 skipped
pytest -q -n 2 tests/integration/test_memory_metadata_contention.py tests/integration/test_vector_retire_race.py tests/integration/test_memory_verify.py tests/integration/test_memory_precondition.py tests/integration/test_memory_by_id.py 61 passed

No statement changes, so tests/analyzer/shapes.txt does not move.

Latency of memory.update_by_id on an idle key: 200 sequential calls over HTTP after 10 warm-up calls, one client, a server from source with the fake embedder and LOOM_AUTH_REQUIRED=false, ClickHouse in a container on the same machine. The machine was shared with other test runs. The two builds were measured in turn, twice each:

Build p50 p99
main, first run 703.9 ms 1320.0 ms
this branch, first run 754.4 ms 935.0 ms
main, second run 931.4 ms 1645.7 ms
this branch, second run 775.1 ms 1463.0 ms

Two runs of one build differ by more than the two builds do (p50 704 ms and 931 ms on main), so the measurement shows no difference. The unit test above is the exact statement: the update sends no statement it did not send on main. The script:

# python measure.py http://localhost:7777 200
import statistics, sys, time, uuid

import httpx

base_url, calls = sys.argv[1], int(sys.argv[2])
key = {"org": f"it-update-latency-{uuid.uuid4().hex[:8]}", "namespace": "notes", "agent": "writer"}
with httpx.Client(base_url=base_url, timeout=60.0) as http:
    created = http.post(
        "/v1/memory.set",
        json={**key, "memory_key": "deploy_window", "memory_type": "semantic", "value": "Deploys happen on Tuesday"},
    )
    memory_id = created.json()["memory_id"]
    took = []
    for n in range(calls + 10):
        body = {"org": key["org"], "memory_id": memory_id, "value": f"Deploys happen on day {n}"}
        started = time.perf_counter()
        answer = http.post("/v1/memory.update_by_id", json=body)
        elapsed = (time.perf_counter() - started) * 1000
        assert answer.status_code == 200 and answer.json()["updated"], answer.text
        if n >= 10:
            took.append(elapsed)
took.sort()
print(statistics.median(took), took[round(0.99 * len(took)) - 1])

Not run here, left to CI: the full unit suite, the integration files outside the lists above, the Postgres-profile integration jobs (no Postgres server was started; the integration race test skips there), the generator checks of make lint, and the dashboard and SDK jobs, whose files this diff does not touch. A first local run of tests/integration/same_key, test_conflict_resolver_ch.py, test_memory_code_links.py and test_cross_principal_leakage.py as whole files was stopped after ten minutes on the shared machine; the selections in the table replaced it.

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code wrote the diff. The new tests were run and seen to fail on main before the fix; the race and the latency were measured on both builds as listed above; the served 503 of each op was read from a running server.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • Local format, lint, type checks and focused tests pass, as listed under Tests. make format and make lint were not run as a whole: ruff, the two gates and Prettier were run on what changed. The full make test-unit and applicable integration results are reported by CI; a full local run is not required before pushing.
  • Generated files are regenerated in this PR, not by hand: none is affected. No op, field, setting, table or plugin file changes.
  • A new migration is additive and numbered after the latest on main; no merged migration is edited. None added.
  • A behaviour change to any file a plugin ships bumps both plugin manifests' version. None changed.
  • The frontend builds and its tests pass, if frontend/ changed. Not changed.
  • Docs under docs/ describe the system as it now is (docs/architecture/memory-architecture.md, docs/architecture/storage-authority.md), and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers (tests/unit/test_public_copy.py passes).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.
  • I signed the Contributor License Agreement (CLA) if CLA assistant requested a signature: none was requested when this was written.

🤖 Generated with Claude Code


Note

Medium Risk
Changes concurrency semantics on the hot memory update path: overlapping writes now get 503 instead of silent 200 with lost or reverted edits; callers must retry or re-read.

Overview
Fixes a concurrency bug where memory.update and memory.update_by_id could return 200 while their revision never became head (buried under memory.verify or another write of the same key).

Revisions are now committed only over the exact head they were built from: ClickHouse inserts pass expected_heads into insert_memory_versions; Postgres always rechecks with heads_unchanged(exact=True). The optional exact / if_match_sha256-only path for unconditional updates is removed. When the head moves between read and insert, the op answers 503 ADMISSION_CONTENDED and writes no version row or search document.

Architecture docs are updated to describe the same rules for memory.update, memory.update_by_id, and Postgres admission. Tests add unit and integration races between update and verify, adjust stubs to return the expected head, and expect memory.update to be refused when a newer high write wins during embedding.

Reviewed by Cursor Bugbot for commit 8a51a50. Bugbot is set up for automated code reviews on this repo. Configure here.

zlareb1 and others added 2 commits December 5, 2026 04:34
…eing buried

memory.update and memory.update_by_id build a revision from the head they
read: every column the request does not set is copied from that head, and
the version is drawn above it. The insert took the key's fence but did not
compare the head inside it. A write that landed between the read and the
insert was lost either way: a memory.verify that drew the later version
buried an acknowledged update under a copy of the old value, and an update
that drew the later version replaced an attestation it never read.

The revision's insert passes the head it was built from as the expected
head, with or without if_match_sha256. A head that moved since the read
answers 503 ADMISSION_CONTENDED, and no version row and no search document
are written. Under the Postgres authority the commit compares the same
full head state; it compared only the row's protection for an update
without if_match_sha256. The `exact` argument that chose between the two
is removed.

Test stubs that served no head, or another one than the update read, serve
that head. An older memory.update that resumes after a newer write of its
key is refused in the vector retirement race test, where it wrote a row
below the newer one.

Signed-off-by: Mohammad Lareb Zafar <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
main changed docs/architecture/storage-authority.md beside this branch's
paragraphs on the head check; the two sets of edits merge without a
conflict.

Signed-off-by: Mohammad Lareb Zafar <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@vercel

vercel Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
loom-docs Ready Ready Preview Dec 5, 2026 5:36am UTC
loom-telemetry Ready Ready Preview Dec 5, 2026 5:36am UTC

Request Review

In the `("memory.update", False, "sensitivity_sweep")` case of
`test_an_older_writes_late_vector_stays_under_a_newer_high_write` the older
update is refused over the head the sweep relabelled and writes no vector, so
no late vector reaches the sweep's fence. The comment above the case says
that; it named the fence as what covers the key. No case or assertion changes.

Signed-off-by: Mohammad Lareb Zafar <lareb.zafar@clickhouse.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@zlareb1
zlareb1 merged commit 4337926 into main Dec 5, 2026
81 of 82 checks passed
@zlareb1
zlareb1 deleted the fix/update-checks-the-head-it-read branch December 5, 2026 05:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant