Repository navigation
perf(startup): about 0.7 s off the desktop open: lazy chunks and dictionaries, startup steps in parallel, Node compile cache - #13872
Conversation
| (.once (.-webContents win) "did-finish-load" | ||
| (fn [] | ||
| (when-not @*torn-down? | ||
| (reset! *dispose (init-updater {:repo "logseq/logseq" | ||
| :win win}))))) |
There was a problem hiding this comment.
🟡 Updater stops after main-process reload
After a main-process hot reload, setup-updater! waits for another did-finish-load on the already loaded window. stop removed the previous updater handlers, so update checks remain unavailable until the window reloads.
Learn more
The updater setup runs during the main-process lifecycle, not only at window creation. In development, Shadow CLJS calls stop and start on main-process reload. The existing teardown removes the updater IPC handlers through init-updater. At the next setup, the current window has already finished loading, so its one-shot load listener never fires and no handlers are installed.
Example: Reload Electron main-process code while the desktop window stays open. Clicking Check for updates now invokes an IPC channel without a handler; it worked before the reload.
Recommended fix: In setup-updater!, initialize immediately when the window's web contents have already finished loading, and only subscribe to did-finish-load when loading is still pending. Remove any pending listener during teardown.
Was this helpful? React with 👍 or 👎 to provide feedback.
| (loop [pass 0] | ||
| (when (and (first-paint-session-open? session) | ||
| (< pass first-paint-max-passes)) |
There was a problem hiding this comment.
| ;; the released index.html sits beside js/, and the code editor | ||
| ;; module is fetched from there on first use (lazy-editor), not | ||
| ;; loaded by a <script> tag on every open | ||
| :release {:asset-path "./js"} |
There was a problem hiding this comment.
|
7af242c to
6578866
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
4d91dd6 to
9442271
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
9442271 to
9f0e0b0
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
9f0e0b0 to
2656eaa
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
2656eaa to
aa7d600
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
aa7d600 to
011aa05
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
9dea034 to
e52ab3d
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
e52ab3d to
59baedc
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
59baedc to
e345cad
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
e345cad to
aed9393
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
Opening a page mounted, before its first paint, every children subtree that started within 1200 px below the viewport. lazy-block-children decides this in a layout effect through getBoundingClientRect, so each nesting level also forced a layout. On a 700 px window, quantization (92 blocks) shows 13 rows on screen but mounted 54 rows, the lowest at 3169 px, before its first frame. In 1 ms CPU profiles of a cold open that render task took 326-362 ms: component code 155 ms, forced layout 71 ms in 4 reads (one per nesting level), mldoc parse 49 ms. The IntersectionObserver fallback, meant to mount the rest with the same 1200 px margin, used the window as its root. #main-content-container still clips rows below its fold, so the margin never applied: after a 700 px scroll, placeholders 551-1023 px below the viewport stayed unmounted for 1.5 s, until scrolled into view. The layout-effect check now mounts only subtrees that reach into the viewport (the margin above it stays), and the observer's root is the scroll container, so its margin applies: subtrees below the fold mount in the frames right after the first paint. Measured over 3 interleaved relaunched runs per build, medians (ranges) of the frame at which every row on screen is in the DOM: - quantization: cold 935 (866-1051) -> 711 (690-752) ms, warm 227 (152-248) -> 92 (68-95) ms, warm2 204 (147-235) -> 112 (107-135) ms - computer vision (389 blocks): cold 887 (569-896) -> 681 (668-774) ms, warm 219 (213-309) -> 131 (110-147) ms, warm2 212 (193-258) -> 128 (80-148) ms - 3 small pages (9-21 blocks), Tracy-Widom distribution (65) and Douglas Lenat (742): within run-to-run spread, except Tracy-Widom warm2 221 (209-233) -> 179 (114-182) ms. Their rows below the fold are top-level rows, which still mount eagerly. The last rows below the fold arrive later: on the 3 pages with deferred rows, the frame at which all initially mounted rows are present moves later in 8 of 9 medians, by 16 to 145 ms.
Opening a page rendered, before its first paint, every row of a list under 64 rows: the page's top-level rows, and every row of a children list whose top was on screen. On a 700 px window, Theory of small talk (13 top-level rows) built 13 rows to show 6, J G Ballard 21 to show 11, Scholasticism 36 to show 16 (19 of its 20 rows below the fold sit in a children list that starts on screen), quantization 54 to show 13. A list of the page outliner that mounts during the page's first paint now renders its first row only. In the task that brings the rows, and again in the frame before the paint, the lists whose rendered rows end above the bottom of the viewport grow, innermost first, until the rows on screen are all there; the rest of each list mounts in the task after the paint. Rows stay direct children of their .blocks-list-wrap, as the editor's sibling walks expect, and render as a prefix of the list with the same keys. A key, pointer or wheel event before the rest mounts renders it first, inside flushSync, from a capture listener on window. Anchor routes, restored scroll offsets, embeds, journals, the sidebar and virtualized lists render as before. Measured on 5 pages, 3 pinned interleaved relaunched runs per build. Rows built before the rows on screen are complete, the same in every run, cold and warm; rows on screen and at settle are unchanged: - Theory of small talk 13 -> 6, J G Ballard 21 -> 12, Scholasticism 36 -> 16, quantization 54 -> 13; countercurrent flow (all rows on screen) 9 -> 9 - on top of the children deferral of perf/row-rendering: 13 -> 6, 19-20 -> 12, 36 -> 16, 16-20 -> 13 Frame at which the rows on screen are complete, medians (ranges): - Theory of small talk: cold 373 (360-1154) -> 333 (225-341) ms, warm 85 (69-86) -> 71 (67-71) ms, warm2 81 (79-83) -> 66 (63-67) ms - J G Ballard: cold 418 (416-418) -> 380 (376-416) ms, warm 119 (79-120) -> 96 (95-103) ms, warm2 72 (72-108) -> 61 (56-89) ms - Scholasticism: cold 693 (686-698) -> 561 (402-633) ms, warm 143 (97-143) -> 96 (68-101) ms, warm2 91 (88-144) -> 88 (59-94) ms - quantization: cold 993 (676-1011) -> 730 (728-744) ms, warm 263 (199-276) -> 90 (72-92) ms, warm2 265 (172-278) -> 86 (57-87) ms - countercurrent flow: cold 371 -> 370 ms, warm 72 -> 80 ms, warm2 68 -> 74 ms, overlapping ranges The DOM at settle, arrow keys and Shift+ArrowDown across the first deferred row, scroll to an anchored row, drag and drop of a deferred row, and Enter at the last row on screen gave the same result as before in the app.
The code editor module (`:code-editor`, CodeMirror and its modes) runs on every app open, though it is only needed when a code block is drawn. `resources/index.html` loads `js/code-editor.js` with a `<script>` tag; in a CPU profile of a desktop window reload it took about 360 ms of the renderer's time before the home screen.
`frontend.components.lazy-editor` already loads the module on demand (`shadow.loader/load :code-editor` when a code block mounts). In a release build the module loader resolves the module to `/static/js/code-editor.js`, the dev `:asset-path`, which does not exist beside a packaged `index.html`; the `<script>` tag hid that. The release build now uses `:asset-path "./js"`, so the module is fetched from beside the page, and the tag is removed from `index.html`.
In a desktop release build the module loader table reads `{"code-editor" ["./js/code-editor.js"]}`, and a profile of a reload shows no `code-editor.js` work before the home screen.
…used The Electron main process loads the MCP SDK and zod, fastify and electron-updater before it creates the main window, through the top-level requires of `electron.mcp-server`, `electron.server`, `electron.updater` and `electron.handler`. In a CPU profile of a desktop app open, those requires took about 210 ms (MCP SDK and `zod/v3`), 115 ms (`electron-updater`) and 65 ms (`fastify`, `@fastify/cors`) of the main process's time before the window. None is needed for the window: the API server and MCP are off by default, and the updater is first used after the page loads. - `electron.mcp-server` requires the SDK modules and zod on first use (the first `/mcp` initialize, or the first MCP server it creates); the tool definitions are built per server from the loaded zod. - `electron.server/start!` requires fastify and `@fastify/cors` when the API server starts. - `electron.updater` requires electron-updater when it is used, and `setup-updater!` sets the updater up when the main window's page has finished loading (its teardown is returned as before); `electron.handler`'s `:quitAndInstall` requires it there too. Checked in a desktop build: with the API server and MCP turned on, an MCP `initialize` over HTTP gets a session and `tools/list` returns listPages, getPage, upsertNodes, searchBlocks, listTags and listProperties; in a CPU profile of the main process before the window, none of the MCP SDK, electron-updater or fastify is loaded.
The two tongue translators were built at namespace load over all 25 locale dictionaries (182 ms of an app open in a renderer profile), while the app shows one locale. Each locale now gets its translator on first use, from its own dictionary, its parent tags' and English for the fallback. A test compares every key of every locale against translators built over every dictionary.
setup-updater! waited for did-finish-load, but a main-process reload in development sets it up again on a window that has already loaded: the event never came, and after the teardown removed the old handlers the updater's IPC channels had none. electron.lifecycle/when-loaded! runs the setup at once on a loaded window and on did-finish-load otherwise. core-test: on a loaded window it runs at once and waits for nothing; on a loading window it runs on did-finish-load.
…es the Node compile cache Every start of the desktop app compiled the main-process bundle (electron.js) from source before the first line of it ran, and the db-worker child process did the same for its own bundle. resources/electron-bootstrap.cjs is now the package entry (resources/package.json "main"). It turns on Node's module compile cache in a node-compile-cache directory under the user data folder, exports that directory as NODE_COMPILE_CACHE so the db-worker child process inherits it, and then requires electron.js. The first start fills the cache; later starts consume the compiled code instead of compiling it again. What is deferred: V8 compilation of the main-process and db-worker bundles, from every start to the first start after an install or update. Not measured on its own yet; this is a separate commit so it can be measured by leaving it out.
…st load of a script By default Chromium only stores compiled code for a script in its code cache after it has seen the script load a few times, so the first starts after an install or update compile the whole renderer bundle from source. The main window now sets webPreferences v8CacheOptions to "bypassHeatCheck", which writes the cache on the first load. What is deferred: renderer-bundle compilation, from the first several starts to the first start only. Not measured on its own yet; this is a separate commit so it can be measured by leaving it out.
…ad of after it The renderer rendered the UI first and only then asked for the db-worker runtime (persist-db/<start-runtime!>), so the two waits were added together. handler/start! now begins <start-runtime!> at the same time as the UI chain and a new startup-ready helper joins them. The app is ready when both are done. If the runtime fails, startup-ready waits for the UI chain to settle before rejecting, so a failure is not published while the UI is still mounting; if the UI fails, it rejects at once. The db-worker-spent-time log line is dropped because the runtime no longer starts after a timestamp taken between the two steps. What is deferred: nothing is skipped; the runtime start no longer waits for the UI render. Tests: startup-ready waits for both, waits for the UI after a runtime failure, and does not wait for the runtime after a UI failure (frontend.handler-test).
frontend.core/start rendered the root and printed the welcome message inline. The two steps are now a private mount! function that start calls; behaviour is the same. This is what is left of an attempt to mount the UI before the rest of startup. That attempt lost the elements other code anchors to and was reverted, so start still mounts at the same point as before.
… is missing On every desktop start the global config handler made sure the config directory and file existed (a mkdir and a file stat over IPC) and then read the file, even though the file exists on every start but the first. global-config-handler/start now reads the file first. Only a missing-file error (ENOENT, including the form wrapped by an IPC "Error invoking readFile" message) creates the file and reads it again; any other read error, such as permission denied, is reported through the existing handler and never creates anything over the file. What is deferred: the directory creation and file existence check, to the first start. Tests: an existing config is read without mkdir or stat; a wrapped ENOENT is recovered by creating the file once; an unreadable config is not created over (frontend.handler.global-config-test).
…together after idb
After idb/start the startup chain awaited get-system-info, then plugin-handler/setup!, one after the other, before the first render. The global config start ran later, in restore-and-setup!, after the current graph was restored and before the restoring flag was cleared.
The three only need idb, not each other, so handler/start! now starts them together with p/all before render. The global config start moves out of restore-and-setup! into that group; it still runs only when global config is enabled, and its options argument (unused by start) is now empty instead of {:repo repo}. The plugin config start stays where it was.
What is deferred: nothing is skipped; the three waits overlap instead of adding up, and the global config load no longer sits on the graph-restore path. Global config is now loaded before the graph is restored rather than after.
On desktop, get-all-graphs asked the db worker for its graph list and only then asked the main process (ipc "getGraphs") for the graphs on disk, although the second request does not use the first result. Both requests now start together with p/all; the merged, de-duplicated result is the same. What is deferred: nothing is skipped; the disk listing no longer waits for the worker listing. Test: the disk listing starts before the worker listing resolves, and the merged result holds both graphs (frontend.db.persist-test).
…e viewport The journals list is virtualized, and a virtualized list renders nothing until it has measured its container, so the first journal appeared a measurement round trip after the data was ready. all-journals now gives the list :initial-item-count 1, and :default-item-height set to the height the placeholder already uses, so the first journal renders on the first pass and the real rows are still measured normally afterwards. What is deferred: the viewport measurement before the first journal can render. Test: the virtual list receives the initial item count and the same default height as the placeholder (frontend.components.journal-test).
…t use frontend.ui initialised Emoji Mart with the full emoji dataset when the namespace loaded, and components.icon converted the same dataset to a Clojure sequence at load, so every start paid for both before any emoji was shown. Both are now delays. ui/ensure-emoji-data! forces the Emoji Mart init and is called where an emoji is first needed: when an emoji icon is rendered, when an emoji button is rendered in the picker, before an emoji search, and before block reactions are rendered. The picker's emoji list is converted once, on the first time the picker needs it, and reused afterwards. What is deferred: Emoji Mart initialisation and the emoji dataset conversion, from every start to the first use of an emoji. Test: the deferred emoji list equals the eager one and is reused between picker opens (frontend.components.icon-test).
logseq.db.frontend.validate built four malli validators and explainers over the whole DB schema (open and closed) when the namespace loaded, in every process that requires it, including every app start. They are now delays. The closed schema is built once and shared by the closed validator and explainer. get-schema-validator and get-schema-explainer deref the delay, so their callers are unchanged. validate-local-db-ents!, which called the closed explainer directly, now goes through get-schema-explainer inside the existing binding of *db-for-validate-fns*, so the explainer is still created and run with that binding in effect. What is deferred: malli compilation of the DB schema, from every load of the namespace to the first validation. Covered by the existing validate tests in deps/db (no new test).
logseq.db-sync.malli-schema compiled a malli coercer for every request and message schema when the namespace loaded, in the app and the sync server alike. ->coercer now returns a function that builds the coercer in a delay on its first call and reuses it afterwards. The def names, the call signature and the failure handler are unchanged. What is deferred: malli compilation of each db-sync schema, from namespace load to the first use of that schema. Test: no coercer is built until the first call, and later calls share the one built (logseq.db-sync.malli-schema-test).
The desktop page (resources/index.html) and published pages loaded pdf.mjs and pdf_viewer3.mjs as module scripts at startup, so PDF.js was fetched and evaluated on every start even when no PDF was opened. Both pages now load resources/js/pdf-loader.js, a small script that defines window.loadLogseqPDF. The first call imports pdf.mjs, then pdf_viewer3.mjs, and later calls share that one import. The PDF loader in extensions/pdf/core waits for loadLogseqPDF before it requests the document. The published-page HTML builder emits the same loader script in place of the two module scripts. What is deferred: fetching and evaluating PDF.js, from every start to the first PDF opened. Test: the exported HTML contains pdf-loader.js and no direct pdf.mjs script (frontend.publishing-home-test).
…azily loaded chunks main.js carried the graph renderer (PixiJS), the AWS Amplify login flow and the whole settings UI although none of them is on screen at startup. Three new shadow-cljs modules, :graph-view, :authentication and :settings, each depending on :main, are declared in the app, mobile and publishing builds: - graph view: frontend.components.lazy-graph is the graph-2d that components.graph and components.page now use. It loads :graph-view on first render and shows an empty canvas until frontend.extensions.graph registers the real renderer. A load failure is thrown into the error boundary. - login: frontend.components.user.login keeps sign-out!, open-login-modal! and page as thin wrappers that load :authentication (the old implementation, unchanged, moved to login_impl.cljs) on first use. handler/start! no longer calls setup-configure! at startup; the implementation namespace configures Amplify when it loads. - settings: frontend.components.lazy-settings has the settings, appearance, collaboration and sync/publish server components, loads :settings on first render and renders the registered component. header, theme, routes and events/ui use it in place of components.settings. The three share one commit because they add adjacent entries to the same module map in the three builds and to the single js-files vector in publishing/export.cljs, so git cannot revert one without a conflict in the others. publishing/export.cljs now lists the three new files so a published graph carries them. What is deferred: loading and evaluating the graph renderer, the Amplify login code and the settings UI, from every start to the first time each is shown. Existing tests for graph, settings and login pass unchanged; there is no new test for the lazy wrappers.
…t-zip when they are used electron.utils required open, node-fetch, extract-zip, https-proxy-agent and socks-proxy-agent while the main process loaded, although a typical start opens no link, fetches nothing through a proxy and extracts no zip. open, node-fetch and the two proxy agents are now delays that are dereferenced at the call site (open, fetch, build-fetch-agent). extract-zip became a function that requires the module on each call; its signature is unchanged, so electron.plugin, which refers to it, needs no change. The delayed vars are private; nothing outside the namespace used them. What is deferred: reading and evaluating these Node modules, from every main-process start to the first use of each. No new test.
electron.context-menu required electron-dl at namespace load, so the main process read the module on every start although downloads only start from the context menu. download is now a private function in the namespace that requires electron-dl on each call and forwards the window, url and optional options, so the two call sites are unchanged. What is deferred: reading and evaluating electron-dl, from every main-process start to the first download. No new test.
…indow is created register-default-protocol-client! (OS registration of the logseq:// scheme) ran in the app-ready setup before the main window was created, so the window waited for it. It now runs on setImmediate right after the main window object is created. Registering the scheme with the OS does not depend on rendering or navigation, and it does not wait for the page to load either, so the window is not held up by it. What is deferred: the OS protocol registration, from before window creation to just after it. It still runs on every start. No new test.
…is used frontend.dicts evaluated all 25 dictionaries (English and 24 other languages) as data when the namespace loaded, in the renderer and in the main process, although one language is shown. The Electron translator was also built over all 25 at once, and the default view titles were collected from all 25 at load. Every dictionary except English is now a delay (the new deferred-edn-resource macro; in Clojure and bb it still yields the data directly). dicts/realize-dict reads one. dicts/locale-dicts, moved from context/i18n so that electron.i18n can share it, realizes only the locale's own dictionary, its parent tags' and English for the fallback. Both translators are built per locale on first use from locale-dicts: context/i18n as before, and electron.i18n in place of its single translator over every dictionary. views.cljs: a translation-values macro collects the default view title strings from the dictionary files at compile time, so the set of titles is the same and no dictionary is read at run time. What is deferred: evaluating the 24 non-English dictionaries, from every start (both processes) to the first time that language is needed. Tests: locale-dicts realizes only the locale, its parents and English, and gives only the fallback for an unknown locale; the per-locale translators match one built over all realized dictionaries, with and without the fallback (frontend.context.i18n-test); the Electron translator matches the full one across locale switches, including an unknown locale (electron.i18n-test); the compiled default view titles equal those from every shipped language (frontend.components.views-test).
…oercer test The source calls ma/coercer with four arguments. ma/coercer has several arities, so that call compiles to a direct call of `cljs$core$IFn$_invoke$arity$4` on whatever the var holds. The test's variadic replacement has no such property, so under the db-sync test build the call threw "arity$4 is not a function" (CI's test:node-adapter job). Only a multi-arity fn gets the per-arity properties; the replacement now has the 4-arity the source calls. The code under test is unchanged. The db-sync suite passes: 245 tests, 4462 assertions.
The main process started a graph's worker only when the renderer asked for it, and the renderer asks only after loading and running its scripts: in a cold open the worker process started about 30 ms after DOMContentLoaded, then spent about 400 ms booting and opening the graph while the renderer finished its own work and then waited for it. The main process now remembers the graph a window last asked a worker for and starts that graph's worker for the main window right after creating it, so the worker boots while the renderer loads. The renderer's own call for that graph gets this worker, or waits for its start when it is still in flight: the manager now runs one start per graph at a time, and a call that comes during a start waits for it, then reuses the worker or, when that start failed, starts it again. A call for another graph switches the window's graph the way any graph switch does. A failed prestart is logged and the renderer's call starts the worker as before. Measured on a release build (12 alternating cold opens each, 6 cores, median): the home screen 1242 -> 1137 ms. The first contentful paint moves 817 -> 864 ms, since the worker's boot now shares the CPU with the renderer's script evaluation; on 12 cores the home screen gains 121 ms and the paint moves 10 ms.
…he renderer is idle Startup registered every global shortcut as a palette command before the first render: building them reads each shortcut's binding, and each registration sorted the whole list and updated the state, about 50 ms of the path to the home screen in a startup profile. They are now registered in one state update when the renderer is idle (at the latest 2 s after startup), and any read of the commands before that (the palette, the plugin API's commands, a plugin registering its own) registers them first, so nothing sees a list without them. Publishing still registers them at once.
Every button and menu item merges its class names through cn, which splits them, resolves conflicting size and padding utilities with regexes and joins them again: about 25 ms of rendering the home screen in a startup profile, for a handful of class strings that recur on every render. The merge is now cached by its input string (cleared when it passes 4096 entries), and cn flattens its arguments only when one is a sequence.
…shortcut build-category-map runs at load for every shortcut category, and its filter rebuilt the category's namespace, includes and excludes sets for each of the ~300 built-in shortcuts it looked at. The sets are now built once per category; the selected shortcuts are the same.
aed9393 to
9eb13fd
Compare
… merges cleanly with logseq#13872 The tests this PR added to views_test.cljs sat at the same place as the ones logseq#13872 adds there, so the two PRs conflicted and the nightly merge left one of them out. The tests are unchanged; they now live in frontend.components.views-1398-test, which carries the requires and the render-static helper they need, and views_test.cljs is back to master's.
Startup performance, combined from #13546, #13631, #13633 and #13788 (closed in favour of this one). Each section below is the original description; the commits are unchanged.
perf(block): draw no row below the fold before a page's first paint (was #13546)
This brings #13447 and #13451 into 1 pull request, so they merge once. Both change what an opened page draws before its first paint, and both edit the same block component (
src/main/frontend/components/block.cljs). The branch is on current master. Each part keeps its own commit, unchanged, so the review can go commit by commit. The old pull requests are closed with a link here; their review threads stay there.Commits, in order:
perf(block): mount below-fold children after paint(perf(block): mount below-fold children after paint #13447)perf(block): defer rows below the fold on open(perf(block): defer rows below the fold on open #13451)Tests
The whole unit suite on this branch (master
68a68263bplus these commits), with thedb-worker-nodetarget compiled: atTZ=Etc/GMT+122575 tests, 12850 assertions; atTZ=Pacific/Kiritimati, the date-dependent namespaces, 1520 tests, 9319 assertions: 0 failures, 0 errors.The descriptions of the parts follow, as each pull request had them.
#13447: perf(block): mount below-fold children after paint
What changes
Opening a page mounted, before its first paint, every children subtree whose top lay within 1200 px below the viewport. On a 700 px window,
quantization(92 blocks) shows 13 rows but mounted 54 rows, about 4 screens, before its first frame, in 1 task of 250-356 ms cold and 114-174 ms warm.lazy-block-childrendecides this in a layout effect throughgetBoundingClientRect, so each nesting level also forced a layout: in 1 ms CPU profiles of a cold open, that task spent 71 ms in 4 forced layouts, 155 ms in component code and 49 ms in the mldoc parse.The layout-effect check (
near-block-viewport?) now mounts only subtrees that reach into the viewport; the 1200 px margin above it stays, so content above a scrolled position still mounts before paint and nothing on screen shifts. The IntersectionObserver fallback now takes the page's scroll container as its root (lazy-children-observer-root), so subtrees below the fold mount in the frames right after the first paint.This also fixes the observer's margin. With the window as root,
#main-content-containerclipped the rows below its fold, so the 1200 px margin never applied: after a 700 px scroll, placeholders 551-1023 px below the viewport stayed unmounted for 1.5 s, until scrolled into view. With the scroll container as root, a scroll of 700, 1500 or 2500 px leaves no placeholder within 1200 px of the viewport's bottom edge on the 2 pages checked (quantizationkept 3, 1 and 4 before;computer vision0, 5 and 2).Numbers
Desktop release builds of master (
d9d625847) and of this branch, each shipped as only the renderer bundle in the same nightly app shell, on an imported graph of about 154k blocks. 3 runs per build, alternating build by build, each run relaunching the app per page, then opening it cold and twice warm. Medians (ranges) in ms of the frame at which every row on screen is in the DOM:The 3 small pages (9-21 blocks),
Tracy-Widom distribution(65 blocks) andDouglas Lenat(742 blocks) do not change beyond run-to-run spread: their rows below the fold are top-level rows, which this change leaves eager (top-level rows render eagerly below 64,use-virtual-list-opts).Combined with #13437 (request order), 6 runs per build:
quantizationshows its rows on screen at 312 instead of 406 ms cold (ranges overlap) and at 86-93 instead of 214-234 ms warm.The price is below the fold: on the 3 pages with deferred rows, the frame at which all rows mounted by the old code are present comes later in 8 of 9 medians, by 16 to 145 ms (up to 219 ms combined with #13437). Those rows are 1-4 screens down.
Tests
frontend.components.block.lazy-children-test(new): the layout-effect check mounts subtrees that reach into the viewport, leaves subtrees below the fold to the observer even within the margin, and keeps the margin above; the observer's root is the scroll container only when it holds the subtree. The below-the-fold assertions fail on master.TZ=Etc/GMT+12(2478 tests, 12418 assertions) and the time-zone-dependent namespaces atTZ=Pacific/Kiritimati(1446 tests, 8979 assertions): the only failures are the zone-dependent tests that fix(test): build test dates in local time #13430 fixes (6 and 4 assertions), the same as on master.#13451: perf(block): defer rows below the fold on open
What changes
Opening a page rendered, before its first paint, every row of a list under 64 rows: the page's top-level rows, and every row of a children list whose top was on screen. On a 700 px window,
Theory of small talk(13 top-level rows) built 13 rows to show 6,J G Ballard21 to show 11,Scholasticism36 to show 16 (19 of its 20 rows below the fold sit in a children list that starts on screen), andquantization54 to show 13.Now a list of the page outliner that mounts during the page's first paint renders its first row only. In the task that brings the rows, and again in the frame before the paint, the lists whose rendered rows end above the bottom of the viewport grow, innermost first, until the rows on screen are all there. The rest of each list mounts in the task after the paint.
.blocks-list-wrap, as the editor's sibling walks (get-node-prev-sibling,get-node-next-sibling) expect, and render as a prefix of the list with the same keys.flushSync, from a capture listener onwindow, so input never acts on a partial list. The session, and so its listeners, ends after the first frame once the page's rows are known, an empty page's included; while they load (use-childrenreads nil) it waits. The Library list keeps nil while its blocks load, instead of an empty list.This complements #13447, which defers nested children lists that start below the fold. The 2 branches merge without conflict.
Numbers
Desktop release builds of master (
d9d625847) and of this branch, shipped as the renderer bundle in the same nightly app shell, on an imported graph of about 154k blocks. 3 interleaved relaunched runs per build, each opening the page cold and twice warm.Rows built before the rows on screen are complete. This count was the same in every run, cold and warm. The rows on screen and the rows at settle don't change:
Frame at which every row on screen is in the DOM, medians (ranges) in ms:
Tests
frontend.components.block.first-paint-rows-test(new, 8 tests): when the session waits (rows loading), is scheduled (rows known, none included) or closes at once (a virtualized list); that the Library list reads nil while it loads; which opens defer (a page opened from its route) and which render every row (an open that must reach a row below the fold, anything but the standalone page outliner); how many rows fill the viewport; which list grows first (the innermost that ends above the fold, then its parent); that closing the first-paint session mounts every deferred tail; and filling the viewport on flat and nested lists.TZ=Etc/GMT+12(2482 tests, 12439 assertions) and the time-zone-dependent namespaces atTZ=Pacific/Kiritimati(1446 tests, 8979 assertions). The only failures are the zone-dependent tests that fix(test): build test dates in local time #13430 fixes, and the elapsed-time bounds infrontend.worker.graph-view-testandfrontend.worker.search-test(Unit tests: assert on work done instead of elapsed time #13446), which pass when run alone on a quiet machine.Allow edits from maintainers.
perf(startup): load the code editor only when a code block is drawn (was #13631)
The code editor module (
:code-editor, CodeMirror and its modes) runs on every app open, though it is only needed when a code block is drawn.resources/index.htmlloadsjs/code-editor.jswith a<script>tag; in a CPU profile of a desktop window reload it took about 360 ms of the renderer's time before the home screen.frontend.components.lazy-editoralready loads the module on demand (shadow.loader/load :code-editorwhen a code block mounts). In a release build the module loader resolves the module to/static/js/code-editor.js, the dev:asset-path, which does not exist beside a packagedindex.html; the<script>tag hid that. The release build now uses:asset-path "./js", so the module is fetched from beside the page, and the tag is removed fromindex.html.In a desktop release build the module loader table reads
{"code-editor" ["./js/code-editor.js"]}, and a profile of a reload shows nocode-editor.jswork before the home screen.perf(electron): load the MCP SDK, fastify and the updater when first used (was #13633)
The Electron main process loads the MCP SDK and zod, fastify and electron-updater before it creates the main window, through the top-level requires of
electron.mcp-server,electron.server,electron.updaterandelectron.handler. In a CPU profile of a desktop app open, those requires took about 210 ms (MCP SDK andzod/v3), 115 ms (electron-updater) and 65 ms (fastify,@fastify/cors) of the main process's time before the window. None is needed for the window: the API server and MCP are off by default, and the updater is first used after the page loads.electron.mcp-serverrequires the SDK modules and zod on first use (the first/mcpinitialize, or the first MCP server it creates); the tool definitions are built per server from the loaded zod.electron.server/start!requires fastify and@fastify/corswhen the API server starts.electron.updaterrequires electron-updater when it is used, andsetup-updater!sets the updater up when the main window's page has finished loading (its teardown is returned as before);electron.handler's:quitAndInstallrequires it there too.Checked in a desktop build: with the API server and MCP turned on, an MCP
initializeover HTTP gets a session andtools/listreturns listPages, getPage, upsertNodes, searchBlocks, listTags and listProperties; in a CPU profile of the main process before the window, none of the MCP SDK, electron-updater or fastify is loaded.perf(i18n): build a locale's translator on its first use (was #13788)
Opening the desktop app spends about 180 ms building translations it never uses.
frontend.context.i18nbuilds two tongue translators when the namespace loads,translateandtranslate-strict, each over the dictionaries of every locale (25 of them). tongue'sbuild-translateflattens and resolves aliases in every dictionary it is given, so both translators process all 25 dictionaries, while the app shows one locale. In a renderer CPU profile of an app open (page reload to the home screen, 1010 ms in all),tongue.core/build-translatetakes 182 ms, the largest single cost of the open.The fix builds a translator per locale on its first use (memoized per locale, with or without the English fallback), from that locale's dictionary, its parent tags' (
:zh-Hantfalls back through:zh, as tongue resolves tags), and English for the fallback one.t,t-en,t-localeandtttranslate exactly as before. The first translation in a locale builds one or two dictionaries instead of 25 twice.Test:
per-locale-translators-match-one-over-every-locale-testcompares, for every key of every locale (and for a locale that has no dictionary), the result of the new translators with and without fallback against tongue translators built over every locale's dictionary, as before. It passes, and it fails when the English fallback is left out of the fallback translator.Added: 17 more startup commits, measured (-700 ms to the home screen)
Desktop open, from spawn to the home screen, on the release build of this repo's nightly (upstream master + the open PRs) against the same build with these 17 commits. Every part (renderer, both workers, Electron main) built from the one commit; each app opened with its own settled home; opens alternate between builds every round; all opens at full CPU (no cap engaged).
First paint 2259 -> 1471 ms in the first run. In each run the faster build's spread ends below the slower's median.
What each group buys, by leaving the group out (19 opens each, median home):
Four more candidates (scrollbar measurement, shortcut-map memoization, batched command registration, a react-day-picker date-fns import patch) bought nothing measurable together (-45 ms, within noise) and are not in this PR.
Single commits are within the noise of an open (100-200 ms against a spread of 1.5-7 s), so they are measured as groups. Each commit message says what it defers and why. CI's unit suite passes on this branch.
First use of every deferred part, each in a fresh start of the built app, driven over the DevTools protocol, no console error in any: the graph view (its chunk loads, the canvas draws), the login dialog, settings (three tabs), a PDF (PDF.js absent at startup, loaded on the first open, page 1 rendered), the emoji picker (search and pick) and a block reaction, switching the UI language English -> Deutsch -> Português (Brasil) -> English, Validate graph, and in the main process an external link (
shell.openExternaland theopenmodule), Save Image throughelectron-dl, a proxied fetch throughnode-fetchandhttps-proxy-agent, and the SQLite and EDN exports.Commits:
Start the last graph's db worker with the window (a255b15)
A profile of the db worker's cold start showed the worker starting only when the renderer asks for it, about 30 ms after DOMContentLoaded, and taking about 420 ms from there to listening (Electron node-mode boot, the bundle's compile, module init, opening the graph). The renderer finished its own work and then waited for it.
The main process now remembers the graph a window last asked a worker for (
:db-worker/last-repoin the electron config) and starts that graph's worker for the main window right after creating it. The renderer's own call for that graph gets this worker, or waits for the start in flight: the worker manager now runs one start per graph at a time, and a call that comes during a start waits for it, then reuses the worker or, when that start failed, starts it again. A call for another graph switches the window's graph as any graph switch does; a failed prestart is only logged. Tests:electron.db-worker-prestart-test.Measured on release builds of this branch's head with and without the commit, alternating cold opens, medians:
(The 12- and 4-core rows were measured on the commit's first version, which differed only in how a waiting call handles a failed start.) The home screen comes earlier on every core count. The first paint moves later by the CPU the worker's boot now shares with the renderer's script evaluation, more so with fewer cores.
Less renderer work before the home screen (abe2fbb, 917697a, 4d91dd6)
A profile of the renderer's startup, by app function, showed three pieces of work on the path to the home screen that it does not need:
handler/start!registered every global shortcut as a palette command before the first render: building them reads each shortcut's binding, and each registration sorted the whole list and updated the state. They are now registered in one state update when the renderer is idle (at the latest 2 s after startup), and any read of the commands before that (the palette, the plugin API, a plugin registering its own) registers them first. Tests:frontend.handler.command-palette-startup-test.cn(split, resolve conflicting size and padding utilities with regexes, join), for a handful of recurring class strings. The merge is cached by its input string (cleared past 4096 entries). Tests:logseq.shui.components-cn-test.build-category-mapruns at load for each category and rebuilt the category's namespace, includes and excludes sets for each of the ~300 built-in shortcuts; they are built once per category, selecting the same shortcuts. Tests:frontend.modules.shortcut.category-map-test(compared with the previous filter for every kind of spec).Measured as CPU work in reload profiles of release builds, median of 4 alternating reloads each (the machine was under other load, so wall times are noisy; the CPU work of the touched functions is not):
frontend.handler/start!cnRebase onto master 389b715 (2026-11-16)
Master's fee8315 ("recover startup when last-opened graph is gone", logseq/db-test#1532) changed the same startup step as this PR's "start the db-worker runtime while the UI renders". Both stay: the runtime still starts while the UI renders, and a last-opened graph that is no longer on disk is dropped first (
<discard-missing-electron-current-repo!, thenpersist-db/<start-runtime!, inside the promisestartup-readywaits on), so no worker is started for it.frontend.handler-test,frontend.persist-db-testandfrontend.handler.graph-test(77 tests, master's new ones included) pass.