Skip to content

fix(sync): keep value replacements in one request - #13432

Merged
tiensonqin merged 2 commits into
logseq:masterfrom
yuxi-liu-wired:fix/sync-upload-value-replacement
Sep 26, 2026
Merged

tiensonqin merged 2 commits into
logseq:masterfrom
yuxi-liu-wired:fix/sync-upload-value-replacement

Conversation

@yuxi-liu-wired

@yuxi-liu-wired yuxi-liu-wired commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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-test failed 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-datoms is 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-values collects the [e a] pairs the tx retracts on an existing entity, for cardinality-one attributes. upload-tx-item-group-keys (was upload-tx-item-tempids) gives the :db/retract and :db/add items 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, was upload-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-test and flush-pending-retries-large-upload-chunk-until-server-ack-test require (5001 adds to one block's :block/title must 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 to apply-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 with git am with its author kept. It ports the same grouping to deps/db-sync/src/logseq/db_sync/worker/handler/sync.cljs: replaced-value-attrs, tx-item-group-keys (was tx-item-tempids), and group-range-by-start (was tempid-ranges and tempid-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:

  • both datoms inside the tempid group: 1 request, pass (27 runs);
  • the replacement outside the group in an order the server accepts (both before it, or the add before it and the retract inside): 2 requests, the test's (= 1 requests) fails (2 runs);
  • the retract inside the group and the add after it: the server rejects the first request with "DB write failed with invalid data" for 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

  • New large-upload-chunks-keep-value-replacement-in-one-request-test: a pending tx that replaces the page's :block/updated-at around an unrelated datom, uploaded under a 1-datom cap through prepare-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-test now 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.
  • New tx-batch-keeps-value-replacement-in-one-chunk-test (second commit): handle-tx-batch! with a 506-item tx whose :block/updated-at retract 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 answers tx/reject (4 of 4 assertions fail); with it, 4 assertions, 0 failures.
  • The logseq.db-sync.* namespaces, run from deps/db-sync, at the branch head: 191 tests, 4086 assertions, 0 failures, 0 errors.
  • frontend.worker.db-sync-test with TZ=Etc/GMT+12 and TZ=Pacific/Kiritimati, at the first commit and again at the branch head: 232 tests, 2221 assertions, 0 failures, 0 errors in each.
  • The whole unit suite at the first commit, once in each of those zones: 2477 tests, 12410 assertions each. The only failures are the 3 zone-dependent tests that fix(test): build test dates in local time #13430 fixes (6 assertions at UTC-12, 4 at UTC+14), the same as on master.
  • lint (clj-kondo) on the 2 files of the first commit: 0 errors, 0 warnings. clojure -M:clj-kondo --lint src test in deps/db-sync, as its CI runs it, at the branch head: 0 errors, 0 warnings.

Allow edits from maintainers.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 1 potential issue.

Devin Review

Comment on lines +597 to +599
(and (contains? #{:db/add :db/retract} op)
(contains? replaced [entity attr]))
(conj [::value-replacement entity attr])))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

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: apply-large-tx-entry! in deps/db-sync re-splits every tx entry of 500+ datoms at large-tx-max-chunk-items (500) boundaries, grouping only by tempid. A cardinality-one retract/add pair can therefore still land in different chunks even after this PR — each chunk is applied as its own validated transaction, and a chunk whose retract leaves the entity without a required attribute is rejected (tx/reject). This defeats the fix for the 500–5000-datom range (never split client-side, since max-upload-request-datoms is 5000, but always re-split server-side) and for any >5000-datom request the client does split.

Fix: ported the same grouping to the server chunker — collect the [entity attr] pairs retracted on existing entities (replaced-value-attrs), give the matching add/retract items a shared [::value-replacement entity attr] group key in tx-item-group-keys (renamed from tx-item-tempids, same structure as the client), and merge those ranges in group-range-by-start inside reduce-ordered-tx-chunks. Plus a regression test (tx-batch-keeps-value-replacement-in-one-chunk-test) that drives handle-tx-batch! with a 506-item tx whose retract/add straddle the 500 boundary.

Verified:

  • bb dev:db-sync-test: 191 tests / 4092 assertions, 0 failures with the fix; the new test fails without it (retract split → tx/reject).
  • bb dev:test -v frontend.worker.db-sync-test/large-upload-chunks-keep-value-replacement-in-one-request-test -v frontend.worker.db-sync-test/outliner-upload-chunks-preserve-entities-and-acknowledgment-test: 15 assertions, 0 failures.
  • clj-kondo on the touched files: clean. (Note: bb lint:kondo-git-changes has a pre-existing bug — deps/db prefix-matches deps/db-sync paths, so it can't lint db-sync files; linted directly instead.)

I couldn't push to your fork, so the change is attached as a patch — apply with git am or git apply:

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

yuxi-liu-wired pushed a commit to yuxi-liu-wired/logseq that referenced this pull request Sep 26, 2026
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.
@yuxi-liu-wired

Copy link
Copy Markdown
Contributor Author

The gap was real: apply-large-tx-entry! re-split requests of 500 items or more, grouping only by tempid, so a retract and add that the client kept in one request could land in different server chunks. With only tx-batch-keeps-value-replacement-in-one-chunk-test added to the branch, the server rejected the first 498-item chunk ("DB write failed with invalid data", the block missing :block/updated-at) and the batch answered tx/reject. The patch from the comment above is now on the branch as 8391ece, applied with git am with its author kept and its subject shortened to 50 characters. At the new head the new test passes (4 assertions), the logseq.db-sync.* namespaces pass (191 tests, 4086 assertions), frontend.worker.db-sync-test passes at UTC-12 and UTC+14 (232 tests, 2221 assertions each), and clj-kondo on deps/db-sync reports 0 errors and 0 warnings.

yuxi-liu-wired and others added 2 commits September 26, 2026 20:47
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.
@tiensonqin
tiensonqin force-pushed the fix/sync-upload-value-replacement branch from 8391ece to 8d71116 Compare September 26, 2026 12:47
@tiensonqin
tiensonqin merged commit 5080a45 into logseq:master Sep 26, 2026
16 checks passed
@yuxi-liu-wired
yuxi-liu-wired deleted the fix/sync-upload-value-replacement branch September 30, 2026 20:02
devin-ai-integration Bot pushed a commit that referenced this pull request Oct 1, 2026
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.
devin-ai-integration Bot pushed a commit that referenced this pull request Oct 8, 2026
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.
devin-ai-integration Bot pushed a commit that referenced this pull request Oct 8, 2026
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.
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.

2 participants