Repository navigation
fix(sync): keep value replacements in one request - #13432
Conversation
| (and (contains? #{:db/add :db/retract} op) | ||
| (contains? replaced [entity attr])) | ||
| (conj [::value-replacement entity attr]))) |
There was a problem hiding this comment.
🔴 Large replacements still fail server validation
When a required value's retract and add straddle 500 items, upload-tx-item-group-keys groups them only in the client request. The server's reduce-ordered-tx-chunks splits that request without preserving replacements. Its first transaction fails validation, so the upload stalls.
Learn more
The client now keeps a cardinality-one retract and add in one upload request. For a request containing at least 500 items, apply-tx-entry! dispatches to apply-large-tx-entry!. That function applies separate, validated transactions in groups of at most 500 items, and reduce-ordered-tx-chunks preserves only shared tempids. The client-side replacement key does not reach this server chunker, so a required attribute can be absent at the end of the first server transaction.
Example: An upload contains [:db/retract page :block/updated-at old], 499 unrelated items, and [:db/add page :block/updated-at new]. The client sends them in one request, but the server validates the first 500 items without new and rejects the request.
Recommended fix: Make server-side large-transaction grouping preserve cardinality-one replacements as well, or validate and commit the entire logical request atomically while retaining safe storage batching. Add an integration test exceeding large-tx-min-items with the replacement crossing the 500-item server boundary.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
Review findings — the client-side fix is correct as far as it goes, but it doesn't fully fix the bug because the server re-chunks the same tx entries: Gap: Fix: ported the same grouping to the server chunker — collect the Verified:
I couldn't push to your fork, so the change is attached as a patch — apply with fix(sync): keep value replacements in one server chunk (patch)From c13cfa52dcf2f947a49e824c43c2073fcce18ebe Mon Sep 17 00:00:00 2001
From: Tienson Qin <[email protected]>
Date: Sat, 26 Sep 2026 04:55:07 +0000
Subject: [PATCH] fix(sync): keep value replacements in one server chunk
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+
datoms at chunk boundaries grouping only by tempid, so a cardinality-one
retract/add pair from a client upload could still land in different chunks.
Each chunk is applied as its own validated transaction, and a chunk whose
retract leaves an entity without a required attribute is rejected.
Port the client-side grouping: collect the [entity attr] pairs retracted on
existing entities, give the matching add/retract items a shared group key,
and keep the resulting group inside one chunk.
---
.../logseq/db_sync/worker/handler/sync.cljs | 59 +++++++++++++-----
.../db_sync/worker_handler_sync_test.cljs | 62 +++++++++++++++++++
2 files changed, 104 insertions(+), 17 deletions(-)
diff --git a/deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs b/deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs
index 6da421fb30..f3cdaaffd3 100644
--- a/deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs
+++ b/deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs
@@ -349,8 +349,34 @@
[db attr]
(= :db.type/ref (:db/valueType (d/entity db attr))))
-(defn- tx-item-tempids
- [db item]
+(defn- cardinality-many-attr?
+ [db attr]
+ (= :db.cardinality/many
+ (or (get-in (d/schema db) [attr :db/cardinality])
+ (:db/cardinality (d/entity db attr)))))
+
+(defn- replaced-value-attrs
+ "The [entity attr] pairs whose cardinality-one value the tx retracts on an
+ existing entity. Each chunk is applied as its own transaction, so such a
+ retract sent ahead of the add of the new value can leave the entity without
+ a required attribute and be rejected."
+ [db tx-data]
+ (into #{}
+ (keep (fn [item]
+ (when (and (vector? item)
+ (= :db/retract (first item))
+ (<= 4 (count item)))
+ (let [[_op entity attr] item]
+ (when (and (not (tempid? entity))
+ (not (cardinality-many-attr? db attr)))
+ [entity attr])))))
+ tx-data))
+
+(defn- tx-item-group-keys
+ "Keys of the groups a tx item belongs to. Items sharing a key stay in one
+ chunk: those of a tempid, which resolves within a transaction, and the
+ retract and adds of a value in `replaced`."
+ [db replaced item]
(cond
(and (map? item) (tempid? (:db/id item)))
#{(:db/id item)}
@@ -358,13 +384,16 @@
(and (vector? item)
(contains? #{:db/add :db/retract :db/cas :db.fn/cas} (first item))
(<= 4 (count item)))
- (let [[_op entity attr value] item]
+ (let [[op entity attr value] item]
(cond-> #{}
(tempid? entity)
(conj entity)
(and (ref-attr? db attr)
(tempid? value))
- (conj value)))
+ (conj value)
+ (and (contains? #{:db/add :db/retract} op)
+ (contains? replaced [entity attr]))
+ (conj [::value-replacement entity attr])))
(and (vector? item)
(contains? #{:db/retractEntity :db.fn/retractEntity} (first item))
@@ -389,27 +418,23 @@
(recur (next remaining) [[start end]]))
merged)))
-(defn- tempid-ranges
+(defn- group-range-by-start
[db tx-data]
- (let [ranges-by-tempid
+ (let [replaced (replaced-value-attrs db tx-data)
+ ranges-by-key
(reduce-kv
(fn [acc idx item]
- (reduce (fn [acc* tempid]
- (update acc* tempid
+ (reduce (fn [acc* group-key]
+ (update acc* group-key
(fn [[start end]]
[(if (some? start) (min start idx) idx)
(if (some? end) (max end idx) idx)])))
acc
- (tx-item-tempids db item)))
+ (tx-item-group-keys db replaced item)))
{}
tx-data)]
- (merge-ranges (vals ranges-by-tempid))))
-
-(defn- tempid-range-by-start
- [db tx-data]
- (let [ranges (tempid-ranges db tx-data)
- range-by-start (into {} (map (fn [[start end]] [start end]) ranges))]
- range-by-start))
+ (into {} (map (fn [[start end]] [start end])
+ (merge-ranges (vals ranges-by-key))))))
(defn- next-ordered-tx-group
[tx-data range-by-start idx]
@@ -425,7 +450,7 @@
[db f init tx-data]
(let [tx-data (vec tx-data)
item-count (count tx-data)
- range-by-start (tempid-range-by-start db tx-data)]
+ range-by-start (group-range-by-start db tx-data)]
(loop [idx 0
chunk []
acc init]
diff --git a/deps/db-sync/test/logseq/db_sync/worker_handler_sync_test.cljs b/deps/db-sync/test/logseq/db_sync/worker_handler_sync_test.cljs
index 3bb9c52dff..52692a8a6a 100644
--- a/deps/db-sync/test/logseq/db_sync/worker_handler_sync_test.cljs
+++ b/deps/db-sync/test/logseq/db_sync/worker_handler_sync_test.cljs
@@ -2066,6 +2066,68 @@
(is (= 70 (block-title-prefix-count @conn "large-op-block-")))
(is (= 3 (block-title-prefix-count @conn "large-dependency-"))))))))
+(deftest tx-batch-keeps-value-replacement-in-one-chunk-test
+ (testing "a large tx keeps a cardinality-one retract/add pair in one chunk"
+ (with-memory-sql
+ (fn [sql]
+ (storage/init-schema! sql)
+ (let [conn (storage/open-conn sql)
+ ;; Enable the db-graph transact validation that rejects a block
+ ;; left without a required attribute.
+ _ (d/transact! conn [{:db/ident :logseq.kv/db-type
+ :kv/value "db"}])
+ page-uuid (random-uuid)
+ block-uuid (random-uuid)
+ _ (d/transact! conn [{:block/uuid page-uuid
+ :block/name "replacement-page"
+ :block/title "replacement-page"}
+ {:block/uuid block-uuid
+ :block/title "replacement-block"
+ :block/page [:block/uuid page-uuid]
+ :block/parent [:block/uuid page-uuid]
+ :block/order "a0"
+ :block/created-at 1
+ :block/updated-at 1}])
+ page-ref [:block/uuid page-uuid]
+ block-ref [:block/uuid block-uuid]
+ t-before (storage/get-t sql)
+ filler (vec
+ (mapcat (fn [idx]
+ (let [eid (str "replacement-filler-" idx)]
+ [[:db/add eid :block/uuid (random-uuid)]
+ [:db/add eid :block/title (str "replacement-filler-" idx)]
+ [:db/add eid :block/page page-ref]
+ [:db/add eid :block/parent page-ref]
+ [:db/add eid :block/order "a0"]
+ [:db/add eid :block/created-at idx]
+ [:db/add eid :block/updated-at idx]]))
+ (range 72)))
+ ;; The :block/updated-at retract and add straddle the chunk
+ ;; boundary; split apart, the retract leaves the block without a
+ ;; required attribute and the chunk is rejected.
+ tx-data (vec (concat [[:db/retract block-ref :block/updated-at 1]]
+ filler
+ [[:db/add block-ref :block/updated-at 2]]))
+ tx-entry {:tx (protocol/tx->transit tx-data)
+ :tx-id (random-uuid)
+ :outliner-op :save-block}
+ self #js {:sql sql
+ :conn conn
+ :schema-ready true}
+ tx-report-count (atom 0)
+ response (try
+ (d/listen! conn ::replacement-chunks
+ (fn [_tx-report]
+ (swap! tx-report-count inc)))
+ (with-redefs [ws/broadcast! (fn [& _] nil)]
+ (sync-handler/handle-tx-batch! self nil [tx-entry] t-before))
+ (finally
+ (d/unlisten! conn ::replacement-chunks)))]
+ (is (= "tx/batch/ok" (:type response)))
+ (is (= 1 @tx-report-count))
+ (is (= 2 (:block/updated-at (d/entity @conn block-ref))))
+ (is (= 72 (block-title-prefix-count @conn "replacement-filler-"))))))))
+
(deftest tx-batch-applies-large-delete-entry-with-descendants-across-chunks-test
(testing "delete-blocks descendant expansion is still applied in ordered chunks"
(with-memory-sql
--
2.34.1
|
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+ datoms at chunk boundaries grouping only by tempid, so a cardinality-one retract/add pair from a client upload could still land in different chunks. Each chunk is applied as its own validated transaction, and a chunk whose retract leaves an entity without a required attribute is rejected. Port the client-side grouping: collect the [entity attr] pairs retracted on existing entities, give the matching add/retract items a shared group key, and keep the resulting group inside one chunk. Patch c13cfa52 from the Devin review bot's comment on logseq#13432, applied with git am, author header kept. Subject shortened to 50 characters.
|
The gap was real: |
A large upload is split into requests of at most
max-upload-request-datoms, and the chunker kept only the items of a
tempid together. The retract and the add that replace a cardinality-one
value on an existing entity could land in different requests. The
server validates each request as a whole transaction, so a request
holding the retract of a required attribute without its add was
rejected ("DB write failed with invalid data").
When the tx retracts a cardinality-one value on an existing entity, keep
that retract and the adds of the same entity and attribute in one group,
as tempid items are grouped. Plain adds on an existing entity stay
ungrouped, as flush-pending-does-not-overgroup-existing-lookup-refs-test
requires; an add sent alone replaces the old value and is valid.
The outliner upload test hit this: its insert also replaces the page's
:block/updated-at, and the position of those datoms in the tx varies
between runs. When the retract fell inside the tempid group and the add
after it, the server rejected the first request (about 1 run in 12
here). When both came before the group they went in a request of their
own, and the test's "exactly 1 request" failed. The test now asserts
its stated promise instead: exactly 1 request carries the inserted
blocks' datoms.
large-upload-chunks-keep-value-replacement-in-one-request-test uploads a
replacement that straddles an unrelated datom under a 1-datom cap
through prepare-upload-tx-entries and applies each request on a server
copy; it fails on the old chunker every run.
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+ datoms at chunk boundaries grouping only by tempid, so a cardinality-one retract/add pair from a client upload could still land in different chunks. Each chunk is applied as its own validated transaction, and a chunk whose retract leaves an entity without a required attribute is rejected. Port the client-side grouping: collect the [entity attr] pairs retracted on existing entities, give the matching add/retract items a shared group key, and keep the resulting group inside one chunk. Patch c13cfa52 from the Devin review bot's comment on logseq#13432, applied with git am, author header kept. Subject shortened to 50 characters.
8391ece to
8d71116
Compare
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+ datoms at chunk boundaries grouping only by tempid, so a cardinality-one retract/add pair from a client upload could still land in different chunks. Each chunk is applied as its own validated transaction, and a chunk whose retract leaves an entity without a required attribute is rejected. Port the client-side grouping: collect the [entity attr] pairs retracted on existing entities, give the matching add/retract items a shared group key, and keep the resulting group inside one chunk. Patch c13cfa52 from the Devin review bot's comment on #13432, applied with git am, author header kept. Subject shortened to 50 characters.
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+ datoms at chunk boundaries grouping only by tempid, so a cardinality-one retract/add pair from a client upload could still land in different chunks. Each chunk is applied as its own validated transaction, and a chunk whose retract leaves an entity without a required attribute is rejected. Port the client-side grouping: collect the [entity attr] pairs retracted on existing entities, give the matching add/retract items a shared group key, and keep the resulting group inside one chunk. Patch c13cfa52 from the Devin review bot's comment on #13432, applied with git am, author header kept. Subject shortened to 50 characters.
The server-side chunker in apply-large-tx-entry! splits tx entries of 500+ datoms at chunk boundaries grouping only by tempid, so a cardinality-one retract/add pair from a client upload could still land in different chunks. Each chunk is applied as its own validated transaction, and a chunk whose retract leaves an entity without a required attribute is rejected. Port the client-side grouping: collect the [entity attr] pairs retracted on existing entities, give the matching add/retract items a shared group key, and keep the resulting group inside one chunk. Patch c13cfa52 from the Devin review bot's comment on #13432, applied with git am, author header kept. Subject shortened to 50 characters.
What changes
A large upload no longer splits the retract and the add that replace a value on an existing entity across two requests. Such a split made the server reject the first request, and it is why
outliner-upload-chunks-preserve-entities-and-acknowledgment-testfailed intermittently. That test also now asserts the promise its message states instead of a request count. The second commit makes the server keep such a pair in one chunk when it splits a request of 500 items or more.Mechanism
A pending tx larger than
max-upload-request-datomsis sent in chunks (next-large-upload-request-chunk). The chunker keeps the items of each tempid in one request, because the server resolves tempids within a request. Nothing kept a value replacement together:[:db/retract e :a old]and[:db/add e :a new]on an existing entity are separate groups and can fall into different requests. The server validates each request as a whole transaction (apply-tx-entry!), so a request that retracts a required attribute without the matching add is rejected with "DB write failed with invalid data".upload-replaced-valuescollects the[e a]pairs the tx retracts on an existing entity, for cardinality-one attributes.upload-tx-item-group-keys(wasupload-tx-item-tempids) gives the:db/retractand:db/additems of those pairs the key[::value-replacement e a]. Items sharing a key are ranged and merged as tempid items already were (upload-group-range-by-start, wasupload-tempid-range-by-start), so the retract, the add, and anything between them go in one request.Only replacements that include a retract are grouped. Plain adds on an existing entity stay ungrouped, as
flush-pending-does-not-overgroup-existing-lookup-refs-testandflush-pending-retries-large-upload-chunk-until-server-ack-testrequire (5001 adds to one block's:block/titlemust still split); an add sent alone replaces the old value and is valid. A first version grouped every add and retract by entity and attribute and failed those 2 tests.In the app the cap is 5000 datoms, so this affects large uploads such as imports and big pastes.
The server splits again.
apply-tx-entry!sends a tx entry of 500 items or more toapply-large-tx-entry!, which transacts it in chunks of at most 500 items (reduce-ordered-tx-chunks), each validated on its own, and that chunker also grouped only by tempid. A replacement kept in one request by the client could still be split there, and the chunk holding the retract was rejected. The second commit, 8391ece, is the review bot's patch c13cfa52, applied withgit amwith its author kept. It ports the same grouping todeps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs:replaced-value-attrs,tx-item-group-keys(wastx-item-tempids), andgroup-range-by-start(wastempid-rangesandtempid-range-by-start).How the test showed it
The outliner upload test inserts 6 blocks under a 15-datom test cap. The insert also replaces the page's
:block/updated-at, datoms with no tempid, and their position in the tx varies between runs. Writing the tx to a file before each request (30 runs on master) showed three outcomes:(= 1 requests)fails (2 runs);page 1, missing:block/updated-at, and the test errors (1 run).On master the test failed or errored in 10 of 111 runs alone. With only the assertion changed it still errored in 6 of 70.
Tests
large-upload-chunks-keep-value-replacement-in-one-request-test: a pending tx that replaces the page's:block/updated-ataround an unrelated datom, uploaded under a 1-datom cap throughprepare-upload-tx-entries, each request applied on a server copy. On master the server rejects request 0, every run; on this branch every request applies and the server ends with both changes.outliner-upload-chunks-preserve-entities-and-acknowledgment-testnow counts the requests that carry the inserted blocks' datoms (by their tempids) and asserts there is exactly 1; the total request count is no longer asserted in the insert case. On this branch, 70 runs alone: 70 with 0 failures and 0 errors.tx-batch-keeps-value-replacement-in-one-chunk-test(second commit):handle-tx-batch!with a 506-item tx whose:block/updated-atretract and add straddle the 500-item chunk boundary. Without the server change the first chunk (498 items) is rejected with "DB write failed with invalid data", the block missing:block/updated-at, and the batch answerstx/reject(4 of 4 assertions fail); with it, 4 assertions, 0 failures.logseq.db-sync.*namespaces, run fromdeps/db-sync, at the branch head: 191 tests, 4086 assertions, 0 failures, 0 errors.frontend.worker.db-sync-testwithTZ=Etc/GMT+12andTZ=Pacific/Kiritimati, at the first commit and again at the branch head: 232 tests, 2221 assertions, 0 failures, 0 errors in each.clojure -M:clj-kondo --lint src testindeps/db-sync, as its CI runs it, at the branch head: 0 errors, 0 warnings.Allow edits from maintainers.