Repository navigation
perf(editor): less work per keystroke and per delete - #13547
yuxi-liu-wired wants to merge 8 commits into
Conversation
There was a problem hiding this comment.
Devin Review found 1 potential issue.
1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)
| (catch :default error | ||
| (if-let [owner (deleted-owner-uuid db resource-key)] | ||
| [#{[:entity owner]} nil] | ||
| (throw error))))) |
There was a problem hiding this comment.
🟡 Invalid resource requests pass for deleted owners
When an owner is missing, render-resource converts malformed resource requests into successful nil snapshots. block-display-properties validates its context inside the caught renderer, so invalid contexts no longer fail.
Learn more
Resource keys can contain both an owner UUID and other required arguments. render-resource catches every renderer error and treats it as a deleted-owner race whenever the owner UUID is missing. block-display-properties validates the context inside that catch boundary, so invalid context becomes a ready nil resource instead of a rejected request. This also conflicts with the repository's fail-fast rule for programmer errors.
Example: Request [:block-display-properties missing-uuid {:page-title? true}] with an unknown UUID. The incomplete display context is accepted as a nil resource; the same request for an existing UUID fails validation.
Recommended fix: Catch only the missing-owner error identified by common/entity-by-uuid!, or validate each renderer's complete key and arguments before the missing-owner fallback. Preserve errors unrelated to the absent entity.
Was this helpful? React with 👍 or 👎 to provide feedback.
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
cf0eed1 to
af9f90c
Compare
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
af9f90c to
455d81f
Compare
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
There was a problem hiding this comment.
🟡 Changes recommended
Deleted-owner fallback still masks malformed arguments in several resource renderers.
1 open finding
What changed in this PR
Optimizes editor keystrokes, reactive state updates, and selection deletion while improving deleted-resource handling.
Changes:
- Moves editor bookkeeping outside reactive app state and adds path-aware subscription invalidation.
- Deletes selections without a worker pre-read and focuses the prior block immediately.
- Handles resources whose owning block was deleted and adds regression coverage.
| File | Description |
|---|---|
deps.edn |
Uses the incremental-subscription rfx fork. |
src/main/frontend/rfx.cljs |
Adds changed-path subscription invalidation. |
src/main/frontend/state.cljs |
Moves editor bookkeeping into atoms. |
src/main/frontend/components/block/comments.cljs |
Removes obsolete key-code state writes. |
src/main/frontend/handler/block.cljs |
Extracts linked-block DOM identity mapping. |
src/main/frontend/handler/editor.cljs |
Sends selection deletes without pre-reading. |
src/main/frontend/db/transact.cljs |
Runs delete editor callbacks on send. |
deps/outliner/src/logseq/outliner/op.cljs |
Resolves selection deletes in the worker. |
src/main/frontend/worker/handler/render_resource/common.cljs |
Marks missing-entity errors. |
src/main/frontend/worker/handler/render_resource/engine.cljs |
Returns nil resources for deleted owners. |
src/main/frontend/worker/handler/render_resource/property.cljs |
Validates display context before lookup. |
src/test/frontend/state_test.cljs |
Updates cursor-state cleanup. |
src/test/frontend/handler/editor_test.cljs |
Tests cut without a pre-read. |
src/test/frontend/handler/editor_async_test.cljs |
Tests delete send and focus timing. |
src/test/frontend/db/transact_test.cljs |
Tests send-time callbacks and failures. |
deps/outliner/test/logseq/outliner/op_test.cljs |
Covers worker-side selection resolution. |
src/test/frontend/worker/handler/render_resource_test.cljs |
Covers deleted-owner resource batches. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| (render db resource-key runtime) | ||
| (catch :default error | ||
| (if-let [owner (deleted-owner-uuid resource-key error)] | ||
| [#{[:entity owner]} nil] |
There was a problem hiding this comment.
Fixed: block-reactions, page-membership and views now check their other arguments (the user uuid; the membership kind, its shape and the quick-add user uuid; the view feature type) before the owner lookup, so a malformed request fails whether the owner is live or deleted. The test adds those four malformed keys with a deleted owner (each rendered a ready nil before) and the same resources with good arguments, which render as nil.
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
15b4708 to
0211ac5
Compare
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
logseq#13545, logseq#13546 and logseq#13547 replace the 9 open pull requests they bundle; logseq#13468, logseq#13437, logseq#13475 and logseq#13528 are in upstream master.
…store Every keystroke wrote four values through state/set-state!: the block text, the last input time, the last key code, and the saved cursor position. Each write makes the state store re-evaluate every mounted subscription, so on a page with many blocks a keystroke ran that sweep four times. The last input time, the last key code, the saved cursor, and the UI's last key code are read imperatively by the editor handlers through their getters; no component subscribes to them. Keep them in plain atoms, remove their keys from the store's initial state and from the places that reset them, and drop the store save/restore of the saved cursor from state_test. A keystroke now writes the store once, for the text. Measured on a 2,000-page graph, typing into a block on a 204 KB page (key press to next frame, p50 / p90 / max, 83 keys): before 44.7 / 50.7 / 66.3 ms, after this change 34.9 / 49.5 / 88.3 ms.
:editor/last-key-code was only ever written, never read (the store key had no getter; the keyup handler stored a map that nothing consumed). Keeping it as a private atom preserves dead bookkeeping, so remove the atom, the setter, and its call sites entirely.
state/set-state! and state/update-state! know which app-db path they change, and frontend.state registers every state key k as a subscription [k & path] reading (get-in (get db k) path). Tell the rfx store both facts: bind store/*changed-paths* around next-state! and install a sub-key fn that maps [k & path] to [k (first path)] and [::state-key k] to [k nil]. The store then evicts and recomputes only the subscriptions reading those paths on each write instead of every mounted subscription. Writes without a path (swap-state!, event :db effects) are handled by the store's two-level comparison of the previous and next db. Depends on the rfx change "Recompute only the subscriptions that read a changed app-db path"; deps.edn points at that commit on the fork and will be repointed to upstream rfx once that change merges. Measured on a 2,000-page graph, on a 204 KB page: moving the editing cursor between blocks with ArrowDown/ArrowUp (key press to next frame, p50 / p90 / max) 44.4 / 50.2 / 76.5 ms before, 20.8 / 31.2 / 47 ms after the full set of changes; a click into a block paints after 48 ms instead of 160 ms; long tasks over 50 ms during 40 block moves: 38 before, 0 after.
set-state! took a :changed-paths option that no caller passes; replace-state! already reports the written path to the store.
get-render-snapshots failed its whole batch when one resource named a block the worker no longer has, and the page fell to its error screen. A delete op can reach the worker before a snapshot batch that the renderer queued earlier, so a resource whose owner uuid (the key's second element, the owner the renderer's delta handling reads) names no entity now renders as nil and watches that entity, as view-data and block-breadcrumb already do for missing targets.
Deleting selected blocks read them from the worker first, only to keep the top-level blocks and to skip a selection of recycle roots. The op now carries the selected ids with a :selection option and the worker resolves it inside :delete-blocks into the ops the window used to send, so the recorded ops are unchanged. The editor moves to the block above when the op is sent instead of when the worker replies; the deleted rows still leave when the delta arrives.
render-resource took any renderer error for a deleted-owner race when the key's owner uuid named no entity, so a bad request for a deleted block (an invalid display context) rendered as nil instead of failing. entity-by-uuid! now marks its missing-entity failure with the uuid it looked for, and only that failure for the key's owner renders as nil. block-display-properties checks its context before it looks the block up, so a bad context fails whether or not the block exists.
A deleted owner renders a resource as nil instead of failing its batch, but block-reactions, page-membership and views looked up the owner before checking their other arguments, so a malformed request such as [:block-reactions missing-uuid "not-a-uuid"] also rendered as nil while its owner was gone. They now check the user uuid, the membership kind and shape, and the view feature type first: a bad argument fails the request whether the owner is live or deleted. Tests: the four malformed keys fail with a deleted owner (each rendered nil before), the same resources with good arguments render as nil.
0211ac5 to
280f6f2
Compare
|
Combined with the other PRs that change the same files into #13782. |

This brings #13210, #13213 and #13479 into 1 pull request, so they merge once. All 3 edit
src/main/frontend/handler/editor.cljs, and #13213 was already stacked on #13210. The branch is on current master. Each part keeps its own commits, unchanged, so the review can go commit by commit;refactor: drop write-only last-key-code bookkeepingis the maintainer's commit from #13210. The old pull requests are closed with a link here; their review threads stay there.Commits, in order:
enhance(editor): keep per-keystroke bookkeeping out of the app state store(enhance(editor): keep per-keystroke bookkeeping out of the app state store #13210)refactor: drop write-only last-key-code bookkeeping(enhance(editor): keep per-keystroke bookkeeping out of the app state store #13210)enhance(state): only re-evaluate subscriptions that read a changed path(enhance(state): only re-evaluate subscriptions that read a changed path #13213)refactor(state): drop the unused changed-paths option(enhance(state): only re-evaluate subscriptions that read a changed path #13213)fix(worker): nil resources for deleted blocks(perf(editor): delete selection without pre-read #13479)perf(editor): delete selection without pre-read(perf(editor): delete selection without pre-read #13479)Tests
The whole unit suite on this branch (master
68a68263bplus these 6 commits), with thedb-worker-nodetarget compiled: atTZ=Etc/GMT+122570 tests, 12816 assertions; atTZ=Pacific/Kiritimati, the date-dependent namespaces, 1521 tests, 9322 assertions: 0 failures, 0 errors.The descriptions of the parts follow, as each pull request had them.
#13210: enhance(editor): keep per-keystroke bookkeeping out of the app state store
What changes
A keystroke in the editor writes the app state store once (the block text) instead of 5 times.
Mechanism
Every keystroke wrote
:editor/content,:editor/last-input-time,:editor/last-key-code,:editor/last-saved-cursorand:ui/global-last-key-codethroughstate/set-state!. Each write makes the rfx store re-evaluate every mounted subscription, so on a page with many blocks a keystroke paid that sweep 5 times. Nothing subscribes to the 4 bookkeeping values; they are read imperatively (state/input-idle?,state/get-editor-last-pos,state/get-ui-last-key-code). They now live in plain atoms infrontend.state, reset whereclear-edit!andset-editing!reset them, with the same getters and setters.Numbers
Typing into a block on a 204 KB page of a 2,000 page graph, key press to next frame, p50 / p90 / max over 83 keys at a 60 ms cadence, Chromium 148 renderer driven over the DevTools protocol: before 44.7 / 50.7 / 66.3 ms, after 34.9 / 49.5 / 88.3 ms. Keyup handling per key dropped from 32 ms (Event Timing
keyupduration p50) to under 16 ms.Tests
The existing unit suite, compiled with
pnpm cljs:testand run with the grouping ofbb dev:run-test-namespaces(213 namespaces, 2106 tests, 8650 assertions): every test passes exceptfrontend.handler.db-based.import-test/import-from-sqlite-db-persists-import-marker-through-worker-test, whose 5 assertions fail identically on unpatched master (be800f1) whenever that namespace shares a node process with the 6 namespaces the runner groups it with, and pass when the namespace runs alone. With one node process per namespace the suite is fully green on this change. No new test: the change moves values between storage mechanisms with identical getters.Link to Devin session: https://app.devin.ai/sessions/a0806935382643ff89101cd35b49ffdb
Open in Devin Desktop: https://app.devin.ai/desktop/session/a0806935382643ff89101cd35b49ffdb?variant=devin
Requested by: @tiensonqin
#13213: enhance(state): only re-evaluate subscriptions that read a changed path
What changes
A write to the app state store re-evaluates only the subscriptions that read the changed path instead of every mounted subscription.
Mechanism
Depends on the rfx change "Recompute only the subscriptions that read a changed app-db path".
deps.ednpoints at that commit on the fork; it will be repointed to upstream rfx once that change merges.state/set-state!andstate/update-state!know which app-db path they change, andfrontend.stateregisters every state keykas a subscription[k & path]with the single signal[::state-key k]whose function is(get-in value path).frontend.rfxnow tells the store both facts:replace-state-paths!bindsstore/*changed-paths*aroundnext-state!, andsub-keymaps[k & path]to[k (first path)]and[::state-key k]to[k nil](any other subscription is left to its declared signals). Writes without a path (swap-state!, rfx event:dbeffects) fall back to the store's two level comparison of the previous and next db.Concretely, typing rewrites
[:editor/content uuid]and only the popups subscribed to that path are re-evaluated; moving the editing cursor rewrites:editor/editing?and only the 2 blocks whose[:editor/editing? [container-id uuid]]entry changed are re-evaluated, not every mounted block.Numbers
On a 204 KB page of a 2,000 page graph, Chromium 148 renderer driven over the DevTools protocol,
requestAnimationFrameafter each key, p50 / p90 / max: moving the editing cursor between blocks with ArrowDown / ArrowUp, 44.4 / 50.2 / 76.5 ms before the full set of changes and 20.8 / 31.2 / 47 ms after; a click into a block painted after 160 ms (max 240) before and 48 ms (max 64) after; tasks over 50 ms during 40 block moves: 38 before, 0 after. In a CPU profile of typing before this change, the store sweep triggered by the window keydown handler cost about 15 ms per key and the:editor/contentwrite about 12 ms per key; after it,next-state!no longer appears above 1 % of the profile.Tests
The existing unit suite on the 4 branches combined, compiled with
pnpm cljs:testand run with the grouping ofbb dev:run-test-namespaces(213 namespaces, 2106 tests, 8650 assertions): every test passes exceptfrontend.handler.db-based.import-test/import-from-sqlite-db-persists-import-marker-through-worker-test, whose 5 assertions fail identically on unpatched master (be800f1) whenever that namespace shares a node process with the 6 namespaces the runner groups it with, and pass when the namespace runs alone. One wall-clock assertion infrontend.worker.search-test(sync-search-indiceof 300 blocks under 1000 ms with semantic search disabled) measured 1194 ms in one run and passed on reruns; the worker code is untouched by these branches. With one node process per namespace the suite is fully green. The store behaviour itself is tested in the rfx change.#13479: perf(editor): delete selection without pre-read
What changes
Deleting selected blocks (Backspace or Delete on a selection, and the delete step of Cut) went through
cut-selection-blocksinsrc/main/frontend/handler/editor.cljs. It read the selected blocks from the worker (db-async/<get-blocks) only to keep the top-level blocks of the selection and to skip a selection made only of recycle roots, thendelete-blocks!sent:delete-blocks. The editor moved to the block above when the worker replied (run-response-editor-callback!insrc/main/frontend/db/transact.cljs), although the reply of a delete carries no editor rows (operation-row-uuidsreturns none for:delete-blocks). A key pressed before the reply found no editor and was lost.The delete is sent without a read. The window sends the uuids of the selected rows in selection order, with the facts it reads from the DOM as before:
[:delete-blocks [uuids {:selection {:original-ids {...}}}]].:original-idsmaps a rendered linked block to its linking block (originalblockid, the same lookupblock-handler/get-top-level-blocksuses), and on mobile:delete-journals? trueis added.logseq.outliner.op/apply-ops!resolves an op with:selectionagainst the db into the ops the window used to send:outliner-core/blocks-with-level;:logseq.property/deleted-atcounts: the:block/parentof a<get-blocksrow is a ref summary without that attribute, soldb/recycled?never saw a recycled parent there;:delete-pageops.The recorded outliner ops, which undo and sync read, are the ones the window sent before (unit tests below compare them). Page nodes are still deleted as nodes (db-test#1242). Callers of
:delete-blockswithout:selectionare unchanged.The editor moves when the op is sent.
delete-blocks!marks its editor callback with:editor/edit-block-on-send?, andapply-outliner-opsschedules it when it queues the request instead of running it after the reply; the reply then only applies its delta. The target is found in the DOM as before (edit-previous-window-block-fnon the row above the first selected row). The window changes no data: the deleted rows leave when the worker's delta arrives, as before.cut-selection-blocksno longer waits for the reply, socut-blocks-and-clear-selections!clears the selection right after the send.The callback runs at the next animation frame (
on-next-frame!, which the file already has), after the key event is fully dispatched. Two other timings failed on the way:KeyboardShortcutHandlers onwindow, and the editing-only one (:editor/backspace,:editor/delete) receives the key after the one that handles the selection, so it also deleted the last character of the block above.setTimeout0 task, Chromium dispatched a key pressed 10-35 ms after the Backspace before the timer task (a renderer trace shows the delete's keydown task, a frame, the next keydowns, then the timer), and that key found no editor: Shift+ArrowUp landed in 15 of 30 tries on the desktop app.The worker renders the resources of a deleted block as nil (a separate commit, first on the branch).
:thread-api/get-render-snapshotsfailed its whole batch when one resource named a block the worker no longer had, and the page fell to the "Something went wrong" screen. A delete op can reach the worker before a snapshot batch the renderer queued earlier, since the loader sends one batch at a time. Master has the same race in its code; I have not seen it fail there (240 runs of the steps below), and this branch sends the op sooner and keeps the page working while the delete is in flight. In 60 runs of thedeletesteps on the e2e build, with the unit suite running beside them, 2 ended on that screen after:block-display-propertiesfailed for the block just deleted ("Missing renderer resource entity").render-snapshotsnow catches the renderer's failure to find the key's owner (the key's second element, the ownerfrontend.db.subs/apply-delta-storereads), and returns a nil value watching[:entity owner], asmissing-view-dataandblock-breadcrumbalready do for their missing targets; every window consumer of these resources treats nil as not loaded. Only that failure is caught:common/entity-by-uuid!marks its missing-entity error with the uuid it looked for, and any other error, a bad argument or a lookup of another entity, fails the request as for a live block.block-display-propertieschecks its context before it looks the block up, so a bad context fails whether or not the block exists.block-comment-summary-resource-rejects-invalid-uuid-and-thread-testexpected a random uuid to fail; that case moved to the new test.When the worker refuses the delete (a built-in node; the worker broadcasts its notification as before) or fails, the rows stay and the editor stays on the block above; the error is logged as
:editor/delete-selection-failed. Before this change the editor did not move and the selection stayed. The editor is not moved back, since a key typed into it after the delete would be lost again. A selection of recycle roots, or of blocks the worker no longer has, now also leaves the editor on the block above, where before nothing happened.:ui/page-idis no longer computed for this op:apply-outliner-opsremoves it before the worker call and no code reads it.The desktop app, release compiles of the renderer, the db worker and the Electron main from 1 commit each (master
16c4ed1a0and this branch), a new graph without sync, a page of 4 blocks. Each delete selects the last block with Escape and presses Backspace, asdelete-testdoes; each key waits until no worker request has been in flight for 400 ms. Median (range), sessions in the order master, branch, branch, master, 30 deletes each:A key pressed right after the Backspace, as fast as the test driver sends it, 30 times each, 1 session per build (a second master session gave the same counts):
x: it lands in the editor of the block above in 0 of 30 on master (pressed 5.6 - 21.7 ms after the Backspace), 30 of 30 here (7.6 - 30.7 ms);Those branch sessions ran the delete change alone. The branch with both commits, 1 more session of each kind: 13.8 ms (7.5 - 51.2) to the editor, and the letter and Shift+ArrowUp landed 30 of 30 each. No branch session logged a console error.
The e2e web build (
clj-e2edefines, release compile with--debug), master16c4ed1a0against this branch, 3 runs side by side on this machine:outliner-basic-test'sdeletesteps as master has them (Shift+ArrowUp right after the Backspace, without a wait for the editor), repeated 20 times per run on a fresh page: master lost the first Shift+ArrowUp in 8 of 60 iterations (b3's editor mounted after that key), this branch in 0 of 180 (run with the whole unit suite beside it). Backspace to b3's editor mounted, median (p90, max): master 72 ms (330, 504), this branch 20 ms (76, 138). Both builds also end some iterations with no editor (master 3 of 60, this branch 7 of 180), each after the test's second Escape, the race test(e2e): wait out editor races in delete-test #13474 fixes in the test. No iteration ended on the error screen.outliner-basic-test: master 3 of 5 runs pass (failures inconsecutive-backspace-does-not-restore-deleted-blocks-test,backspace-empty-first-child-keeps-empty-parent-subtree-test,delete-end-test,enter-then-tab-on-collapsed-block-expands-it-test), this branch 4 of 4.editor-basic-test: master 0 of 2 runs pass (move-blocks-cmdk,page-ref-navigate-persists-edit-buffer-with-open-popup-test,move-blocks-mod+shift+m), this branch 2 of 2.Tests
logseq.outliner.op-test(deps/outliner/test): the worker keeps the top-level blocks in selection order and records[:delete-blocks [[a11 a b] {}]]for a selection[a11 a a1 b]; a selection of a recycle root resolves to no op, while a block under a recycle root and a recycle root beside a live block are deleted; a rendered linked block deletes its linking block and keeps the target; with:delete-journals?a journal page becomes a:delete-pageop and goes to the recycle bin. On master these 4 tests fail (8 failures).apply-outliner-ops-runs-an-edit-on-send-callback-when-the-op-is-sent-testandapply-outliner-ops-keeps-an-edit-on-send-when-the-worker-fails-testinfrontend.db.transact-test: the request is out and the editor has not moved within the task that sent it; the callback runs at the next animation frame, once, before the reply; it still runs when the worker fails, and the failure reaches the caller. On master they fail (4 failures). A check of the same kind failed against the microtask version.delete-selection-sends-the-selection-and-focuses-the-previous-block-at-sendinfrontend.handler.editor-async-testreplaces the test that asserted the editor moved only from the reply: no worker read before the op, the op carries the selected ids, the editor moves before the reply and not again after it. On master it fails (3 failures).cut-selection-blocks-uses-inner-text-property-value-testinfrontend.handler.editor-testnow checks that Cut sends the inner property-value block without a read (2 failures on master).resources-of-a-deleted-block-do-not-fail-their-snapshot-batch-testinfrontend.worker.handler.render-resource-test: a batch with the display properties and comment summary of a deleted block beside the display properties of a live one renders the first 2 as nil and the third as before; a bad request still throws, for a live block and for a deleted one, and a failure to find another entity than the owner is not taken for a deleted owner. On master it errors.delete-selected-child-page-unlinks-namespace-and-keeps-content,delete-selected-block-still-removes-its-children) pass through the worker path.TZ=Etc/GMT+12(2518 tests, 12547 assertions,logseq.outliner.op-testincluded) and its time-zone-dependent namespaces withTZ=Pacific/Kiritimati(1483 tests, 9100 assertions): 0 failures, 0 errors.Allow edits from maintainers.