Repository navigation
An update that raced another write of its key answers 503 ADMISSION_CONTENDED instead of being buried - #2205
Merged
Merged
Conversation
…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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Changelog category (leave one):
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.updateandmemory.update_by_idno longer lose a write when another write of the same key lands while they run. The update answers 503ADMISSION_CONTENDEDand 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.updateandmemory.update_by_idbuild a revision from the head they read (_write_revisioninserver/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_revisionthen calledinsert_memory_versionswith noexpected_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.verifyis the other write in both; amemory.set, a lock or a sensitivity relabel of the key between the update's read and its insert does the same.mainmemory.verifyreads H, draws a later version and inserts its copy of H with the attestation. The update inserts.new_versionis never the head.memory.verifyreads H and draws its version. The update reads H and draws a later version. The verify inserts, then the update.Fifteen rounds of one
memory.update_by_idand onememory.verifysent together over HTTP for one key, against a server started from source:mainThe fix is one argument:
_insert_revisionpassesexpected_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 raisesAdmissionContendedErrorbefore the insert._land_insertedwrites the search document, the audit row and the announcement only after the memory insert returned, so a refused revision writes none of them.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._commit_revisionrechecks withheads_unchanged(exact=True). It passedexact=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.HeadMovedalready maps toAdmissionContendedError.exactparameter of_land_revision,_land_committedand_commit_revisionis removed: every caller passes the head it read.Alternatives and their cost:
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_CONTENDEDwithRetry-After: 1, where it answered 200. The served detail differs by op, read from a server on this branch:retryablememory.update_by_idtruememory.updatefalseretryable: false(handler_failure_detail). The caller reads the row and sends the update again, as formemory.lock._op_is_idempotentinsdk/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 servedretryable.memory.updateormemory.update_by_id. The memory drawer saves an edit withmemory.set, andserver/operations/dashboard.pylists both ops as not in the dashboard. No dashboard control reaches this refusal.revise_as_pipeline, called fromserver/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._set_tagsinserver/memory/app/decision_extract.py). It reports the refusal for that row (_REPORTED_ERRORSholdsLoomServerError), and the next run reads the row again.docs/reference/errors.mdlists no ops per code.Other writers that insert a memory version without an expected head, from a walk of every call of
insert_memory_versionsandinsert_versions_over_headsunderserver/:memory.update,memory.update_by_id, the rename follower (_insert_revision)memory.verify,memory.lock,memory.unlock, the source redirect ofmemory.move,proposals.decide, expiry (_over_unmoved_heads),_tombstone_ch_heads,_write_tombstone_rowwith a hash or a refused valuemainmemory.unpin,memory.touch,memory.apply(label, demote),memory.restore, namespace rollback,observe.crystallize, the observation distiller, the canonical row ofmemory.consolidate, the sensitivity sweep's relabel,apply_entities_batch,clear_duplicate_tag,write_versions_by_ids,_reject_heads,_write_dependentsmemory.setandmemory.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 commandpublish_rows,send_rows)insert_versions_over_heads, whereexactis 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.memory.sethas 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_preconditioninserver/memory/app/update.py, and no function this diff changes.Compatibility, rollout and rollback
memory.updateandmemory.update_by_idanswer 503ADMISSION_CONTENDEDfor a head that moved during the call. Under Postgres both ops answered that code onmain: withif_match_sha256for any moved head, and without it for a head whose protection moved. On ClickHouse the code is a new answer of the two ops.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.Tests
Run on this branch against a ClickHouse and a server started for it. The new tests were written and run on unchanged
mainbeforeupdate.pywas 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 onmainunder both authorities withDID 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 onmain, 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, onmainand here; under Postgres the commit rechecks the head once._commit_revisionandheads_unchangedagainst a stand-in forpg_publish.committhat calls the recheck on the key's head, ascommit_versionsdoes under the row lock.tests/integration/test_memory_metadata_contention.py::test_update_racing_a_verify_is_the_head_or_is_refused: four rounds ofmemory.update_by_idandmemory.verifysent together over HTTP. Each 200 must be in the head, each refusal must be 503ADMISSION_CONTENDED, one of the two lands every round, and no refused value is inloom.memory_versionsorloom.memory_embeddings. Against a server runningmain'supdate.pyit fails: a verify answered 200 withchangedand the head held no attestation. It skips under the Postgres authority, as the file's other test does.Existing tests changed, assertions kept:
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_fromandtest_memory_fence_publication.py::test_unanswered_high_memory_send_still_fences_search.tests/unit/test_pg_authority.py: the removedexactargument 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 twomemory.updatecases 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 ishigh, it has no live vector, and search does not return it.Runs:
pytest -q -n 2over the 37 unit test files that reach the update handlerspytest -q -n 2over 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)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/analyzertests/analyzeralone: 12 passedpytest -q -n 2 tests/integration/test_memory_metadata_contention.py tests/integration/test_vector_retire_race.pypytest -q -n 2overtests/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.pyandtest_memory_metadata_contention.pypytest -q -n 2 tests/integration/same_key/test_retirement_ch.py tests/integration/test_restored_memory_ids.py tests/integration/test_memory_conflicts.pypytest -q -n 2 tests/integration/same_key tests/integration/test_conflict_resolver_ch.py -k "update or revis"pytest -q -n 2 tests/integration/test_memory_code_links.py -k "update or revis or rename or rewrit"make typecheckruff format --checkandruff checkon the changed files;ruff check server extractor sdk/python tests scripts .claude; the function-length and secret gates; Prettier on the two changed pagesThe rows above ran on the branch's own commit. The branch then merged
main, which changeddocs/architecture/storage-authority.mdbeside this diff's paragraphs, without a conflict. On the merged head:make typecheckpytest -q -n 2over the seven unit files above,test_decision_extract.py,test_memory_code_rename_plan.py, the eight repository scans andtests/analyzerpytest -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.pyNo statement changes, so
tests/analyzer/shapes.txtdoes not move.Latency of
memory.update_by_idon an idle key: 200 sequential calls over HTTP after 10 warm-up calls, one client, a server from source with the fake embedder andLOOM_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:main, first runmain, second runTwo 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 onmain. The script: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 oftests/integration/same_key,test_conflict_resolver_ch.py,test_memory_code_links.pyandtest_cross_principal_leakage.pyas 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
mainbefore 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
make formatandmake lintwere not run as a whole: ruff, the two gates and Prettier were run on what changed. The fullmake test-unitand applicable integration results are reported by CI; a full local run is not required before pushing.main; no merged migration is edited. None added.frontend/changed. Not changed.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.tests/unit/test_public_copy.pypasses).git commit -s), as CONTRIBUTING.md asks.🤖 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.updateandmemory.update_by_idcould return 200 while their revision never became head (buried undermemory.verifyor another write of the same key).Revisions are now committed only over the exact head they were built from: ClickHouse inserts pass
expected_headsintoinsert_memory_versions; Postgres always rechecks withheads_unchanged(exact=True). The optionalexact/if_match_sha256-only path for unconditional updates is removed. When the head moves between read and insert, the op answers 503ADMISSION_CONTENDEDand 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 expectmemory.updateto 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.