Repository navigation
perf(sync): get to the notes sooner on a large initial sync - #12887
Conversation
`pnpm dev:sync-trace` starts two server instances from source in throwaway data directories. Instance A gets a new document with the demo content and acts as the sync server; instance B runs the real "sync from server" setup against a recording HTTP proxy in front of A. No sync code is changed, so the recording shows the protocol exactly as it runs. The run ends once B reports an initialized database and the proxy has been idle for 8 s, long enough to also catch the sync that B's timer starts 5 s after setup. It writes: - trace.json: every exchange with headers and decoded bodies (paged request bodies joined on their last page), plus every log line of both instances with the time it was printed; - index.html: a self-contained viewer that groups the requests into rounds, interleaves the client log, and shows per request what the step does in sync.ts, its entity changes or content hashes, and the raw bodies; it can also open another trace.json; - both logs and both data directories. The instances run with NODE_ENV=development because the production asset path requires a built public/ directory; Vite only compiles on request, so each instance still boots in about 2 s. On the demo document the full sync takes one round: 1,640 entity changes (2.95 MB) arrive in a single pull and nothing is pushed. Assisted-by: Claude Code (Claude Opus 5.5)
`pnpm dev:sync-trace --from-db <document.db>` makes the sync server instance serve a snapshot of an existing database instead of the demo document, so the recording shows how sync behaves at real scale. The original is only read, through `node:sqlite`'s backup API, so it can stay open in a running Trilium. In the snapshot, the unsynced options `syncServerHost`, `syncProxy` and `mfaMethod` are cleared before the instance first starts: a copy of a database that has a sync server would otherwise log into it as that document on its 5 s timer kickoff. The password is replaced through `/api/password/reset` and `/set-password` during one boot with authentication off, because the password options are synced and a direct write would leave their entity changes stale; the instance then restarts with authentication on, so the recorded sync runs against the usual checks. The tool therefore never needs the owner's password or second factor. What changes for every run: - both instances bind to 127.0.0.1 and skip backups; - strings longer than --max-string (2,000 by default) are shortened when recorded, so blob content is neither held in memory nor written out; the full size of every body is still recorded; - the proxy answers before it decodes a response, so parsing an 8 MB pull no longer counts as transfer time; - trace.json and index.html are written one exchange at a time, since the trace of a large database exceeds what one JSON.stringify() result can hold; the output directory is owner-only. On a 2 GB database (202,350 entity changes, 1.85 GB of blob content) the initial sync converges in one round of 17.9 s over loopback: 200 pulls carrying 2.56 GB, 58 apply batches, nothing pushed. The viewer of that trace is 109 MB and loads in about 2 s. Assisted-by: Claude Code (Claude Opus 5.5)
An initial sync of a 2 GB knowledge base (202,350 entity changes,
1.85 GB of blob content) moved 2.56 GB through 200 `/api/sync/changed`
responses: every blob travels base64-encoded inside the JSON, and the
client became usable only once all of it had been fetched, parsed and
applied (17.9 s over loopback). Images and files are 89 % of those
bytes, while notes, branches, attributes and text are about 5 %.
Pulls now leave blobs over 32 KB (`DEFERRED_BLOB_THRESHOLD`) out:
the client sends `deferBlobsOver`, and the server stubs such a blob
exactly as it already does for the mobile `maxBlobContentSize` limit,
empty content with the entity change and its hash untouched, so the
content-hash check passes as before. The route takes the smaller of
the two limits, which leaves `getEntityChangeRow()` unchanged.
After a run converges, `downloadDeferredBlobs()` fetches each stub's
content from the new `GET /api/sync/blobs/:blobId` as
`application/octet-stream`, one at a time, and writes it into the stub
row with `UPDATE ... WHERE LENGTH(content) = 0`. The stubs are the work
list (`LENGTH(content)` takes 10 ms on the 2 GB database, since SQLite
reads a blob's length without loading it), so an interrupted download
resumes after a restart with no extra state. A blob never changes under
its `blobId`, so no entity change is written and no race with a pull
exists: a stub pulled again is fetched again. The download runs outside
the sync mutex so local changes keep syncing during a long download; a
404 skips that blob for the process, and any other error ends the pass
until the next sync.
`ExecOpts.responseType: "bytes"` resolves the body as a `Uint8Array`,
or `null` for a 404, so the downloader reads no error messages. The Node
and Electron provider and the browser `fetch` provider implement it. The
native bridge refuses it: it would carry the bytes as base64 again, and
its only user, the mobile app, keeps a blob size limit, never asks for
deferral, and so never downloads; its stubs stay stubs.
The threshold weighs inline bytes against requests. On this database,
deferring every binary blob would take 4,519 requests and still inline
the large string blobs, since base64 applies to every blob; 256 KB
would leave 465 MB on the wire before the client is usable; 32 KB
leaves 149 MB for 3,240 background requests.
No sync version bump: an old client never sends `deferBlobsOver`, and
an old server ignores it and inlines everything, so a new client never
meets a stub it cannot fetch.
Recorded with `pnpm dev:sync-trace --from-db` on that database:
before after
pull requests 200 (2.56 GB) 27 (242 MB)
usable (hash check) 17.9 s 7.5 s
blob downloads - 3,240 (1.65 GB) in 7.9 s
all content present 17.9 s 15.6 s
Every blob on the client matched the server byte for byte afterwards.
While a blob downloads, its note shows the mobile "open on server"
placeholder and does not refresh once the content arrives; downloads
are not yet checked against the entity change hash.
Assisted-by: Claude Code (Claude Opus 5.5)
The viewer gives `GET /api/sync/blobs/:blobId` a step of its own, with the blob ID and size as its gist, and the summary counts the downloaded blobs and their bytes. The recorder no longer decodes `application/octet-stream` bodies as text, which only produced garbage strings. It now records their size as `bytes`; the first version of this change recorded 0 there, while `wireBytes` was right. Assisted-by: Claude Code (Claude Opus 5.5)
Over loopback a sync request costs about 1 ms and bandwidth is practically unlimited, so a trace cannot show what latency and transfer cost a real client: 3,240 sequential blob downloads took 7.9 s there, while at a 50 ms round trip they would wait about 160 s on round trips alone. `--throttle <bandwidth>,<rtt>` (such as `100mbit,50ms`) makes the recording proxy add half the round trip before a request reaches the server and half before its response starts, and pace request and response bodies through one link per direction. The link is shared: each 256 KB chunk reserves its slot behind every transfer already queued, so concurrent requests split the bandwidth as on a real connection. A per-request limit was rejected because it would let parallel downloads multiply the bandwidth and overstate what parallelism gains. An exchange now ends once its last chunk is sent, so the recorded timings include the simulated transfer. Calibrated on the demo document at 10 Mbit/s and 100 ms: small requests take 102-123 ms, and a 1.41 MB pull 1,241 ms against an expected 1,128 ms of transfer plus 100 ms of round trip. The viewer shows the link in its header, and the Developer Guide page describes the option. Assisted-by: Claude Code (Claude Opus 5.5)
One at a time, a deferred blob download waits a full round trip for
each blob, and an average blob of a large knowledge base (0.54 MB) takes
about as long to transfer at 100 Mbit/s as a 50 ms round trip lasts. On
a 2 GB database over a simulated 100 Mbit/s link with 50 ms of
latency, the 3,240 downloads took 307.6 s: 139 s of transfer plus
162 s spent waiting on round trips, with the link at 45 Mbit/s.
`downloadDeferredBlobs()` now runs `DEFERRED_BLOB_CONCURRENCY` (4)
workers over the same work list. Two or three in flight already fill
such a link; four leaves headroom and stays under the six connections a
browser allows per host. After a failure no worker takes another blob
and the ones in flight finish, as the sequential loop stopped at its
first failure; the rest follow after the next sync.
Recorded with `pnpm dev:sync-trace --from-db ... --throttle
100mbit,50ms`:
one at a time four at a time
blob downloads 307.6 s 143.9 s
link throughput 45 Mbit/s 96 Mbit/s
all content present 335.9 s 172.0 s
The link is saturated now, so further parallelism cannot shorten the
download; only fewer bytes can.
Assisted-by: Claude Code (Claude Opus 5.5)
The server's `compression` middleware offers brotli and gzip on every
sync response, but a client on Node's `http` never sent
`Accept-Encoding`, so it received everything uncompressed: a server
syncing from another server, a desktop with an explicit sync proxy,
and the client instance of `pnpm dev:sync-trace`.
`NodeRequestProvider.exec()` now sends `Accept-Encoding: br, gzip` and
decodes `br`, `gzip` and `deflate` bodies itself, for JSON and for
bytes alike; an encoding it does not know rejects instead of being
parsed as garbage. A desktop without a proxy syncs through
`electron.net`, which, as probed on Electron 45, already sends
`gzip, deflate, br, zstd`, hands the body over decoded and still
reports its `Content-Encoding`. Decoding it again would fail, so the
new `decodesContentEncoding()` hook lets `ElectronRequestProvider` opt
`electron.net` out of both the header and the decoding. Desktop users
without a proxy therefore already received compressed pulls; this
change brings the rest along.
Brotli was chosen over gzip and zstd from traces of a 2 GB database
over a simulated 100 Mbit/s link with 50 ms of latency, compressing
the pulls in the proxy:
usable pulls on the wire compress decompress
none 27.8 s 242 MB - -
gzip 6 18.5 s 72 MB 2,963 ms 447 ms
brotli 4 16.4 s 61 MB 1,407 ms 287 ms
zstd 3 15.1 s 65 MB 497 ms 138 ms
zstd was 1.3 s faster, but the middleware offers no zstd, and brotli
needed no server change. Recorded with real brotli afterwards, the
client was usable after 15.0 s.
Assisted-by: Claude Code (Claude Opus 5.5)
The `compression` middleware treats `application/octet-stream` as compressible, so every deferred blob download was brotli-compressed: on a 2 GB database, 1,735 MB became 1,329 MB on the wire, for about 5 s of server CPU per full sync on a Ryzen 9 9900X, and a multiple of that on the small servers many people sync with. Per owner type, brotli 4 saved: image/png 373 MB 2 % image/jpg 289 MB 14 % application/pdf 620 MB 25 % video/mp4 233 MB 29 % application/json 91 MB 83 % ZIP export's `shouldStoreUncompressed()` was tried first and rejected: it skips PDF, MP4 and JPEG as already compressed, which here threw away 256 MB of saving to spare about 3 s of CPU. Only PNG is excluded, with protected blobs, whose encrypted bytes do not compress, and blobs without an owner. `GET /api/sync/blobs/:blobId` looks the owner up through the `blobId` indexes of notes, attachments and revisions, and sends `Cache-Control: no-transform`, which the middleware honours, for those. Over a simulated 100 Mbit/s link with 50 ms of latency, blob downloads put 1,353 MB on the wire (24 MB more than compressing everything, for 1,132 fewer blobs compressed), and the whole sync took 132.6 s, against 172.0 s uncompressed. Assisted-by: Claude Code (Claude Opus 5.5)
`--compress gzip|br|zstd[:<level>]` makes the recording proxy compress every JSON response of at least 1 KB, as the server's `compression` middleware would pick them, send only the compressed bytes through the throttled link, decompress them and hand the client the original body. That measures an encoding end to end, including one the server does not offer (zstd), without changing the client or the server. The defaults are each encoder's usual level: gzip 6, brotli 4, zstd 3. A response's time then covers compressing, transferring the compressed size and decompressing. A real client decompresses while the body still arrives, so this overstates it slightly. Compressed exchanges record their encoding and both times, `wireBytes` holds the compressed size, and the viewer shows the setting in its header. The constant holding the link's chunk size moved above the top-level `await main()`: declared below it, it was still uninitialized while `main()` ran. Assisted-by: Claude Code (Claude Opus 5.5)
A caller of `RequestProvider.exec()` could not tell a request the server answered with an error from one that never reached it: every provider rejects with a plain `Error` and a message in its own format, so deciding anything from the failure meant parsing that text. The core request module now exports two error types, also from the package index: - `RequestStatusError`, with the `status`, for a response with a status the caller does not accept; the message is unchanged; - `RequestStallError`, for a response that stopped arriving. The second comes with `ExecOpts.idleTimeout`: a request rejects once no part of the response has arrived for that many milliseconds, the wait for the headers included, and every chunk received restarts it. Unlike `timeout`, which bounds the whole transfer, it lets a large body take as long as it keeps arriving. The Node provider, and with it Electron's, runs the timer from the request through the response events and cancels a stalled request with `abort()`, which Electron's `ClientRequest` documents, or `destroy()`, which Node prefers. The fetch provider aborts its controller and, while an idle timeout is set, reads the body chunk by chunk so that each one restarts the timer. The native bridge, which already refuses bytes responses, is left alone. Specs cover both error types on both providers, a body taking longer than the idle timeout while it keeps arriving, and stalls before and after the headers. The steady-body spec passed before the change, as neither provider limited it; it fails once a chunk no longer restarts the timer. Assisted-by: Claude Code (Claude Opus 5.5)
`downloadDeferredBlobs()` ended its pass at the first error of any kind and started the next pass with the same list in the same order, while every download was bounded by the sync timeout over its whole transfer. A blob too large to arrive within that timeout (300 MB on a link under 20 Mbit/s, with the default 120 s) therefore failed on every pass, and every blob listed after it was never downloaded. A download that the server answers with an error status (`RequestStatusError`) or that stops arriving (`RequestStallError`) now fails that blob alone: it stays a stub for the next pass, and the pass moves on; the failures are logged in one line. Any other error, such as a refused or reset connection, would hit every blob alike and still ends the pass. The check goes by the errors' names, so an error class loaded twice still counts. Downloads are bounded by `idleTimeout` set to the sync timeout instead of a total limit, so a large blob on a slow but working link finishes. They also go smallest first. A stub carries no size, so the new `POST /api/sync/blob-sizes` answers the stored size of each blob in a list, which `LENGTH()` reads without loading the content (10 ms on a 2 GB database); blobs of unknown size go last, and without an answer the stored order stays. On that database, the largest 90 of 3,240 blobs carry half of the bytes, and now arrive last. A sync of that database over loopback downloaded all 3,240 blobs in order without a failure, and the client's blobs matched the server's byte for byte. The specs for the skip, the stop and the fallback order each fail when their condition is removed from the code. The skip spec fails every download of the first wave: with one success among them, the old code let a worker take the next blob before the failure had settled, and the spec passed against it. Assisted-by: Claude Code (Claude Opus 5.5)
`--cpu-prof` starts the sync server and the sync client with Node's CPU profiler and writes one `.cpuprofile` per process to `profiles/server/` and `profiles/client/` in the output directory when they exit, so the time of a traced sync can be split between SQL, serialization, compression and idle waiting on each side. Assisted-by: Claude Code (Claude Opus 5.5)
Setting up sync with a 2 GB database spent 7.8 s pulling changes, and a CPU profile of both sides showed each idle for most of it: the client 3.7 s of an 8.4 s window, the server 6.0 s. The pull loop collected responses into 32 MB batches and fired the request for the next one just before applying a batch, but on Node and Electron that request never left during the apply: `NodeRequestProvider.exec()` awaits `getProxyAgent()` and the client before it creates the request, and Node writes it to the socket on a later turn of the event loop, which the synchronous apply blocks. The trace shows each request starting only once the apply ended, so the server prepared nothing while the client wrote. Each response is now applied in its own transaction, once the request for the next one has been sent. `ExecOpts.onSent` reports that point: the Node provider, and with it Electron's, calls it on the request's `finish` event, the fetch provider right after `fetch()`, which the browser sends from outside the worker, and the native bridge after posting the request. The pull waits for it, or for the response if a provider never calls it. The batches existed because a commit was said to carry a large fixed cost. Replaying the client's writes for this database (143k changes) into a fresh database put commits at 0.74 s with 40,000 changes per transaction against 1.04 s with 2,000, about 80 ms more over the whole sync at the 5,000 to 20,000 changes a response carries. That is measured on desktop only; mobile already applied about one response at a time, so of the standalone builds only the desktop browser one, which batched 16 MB, changes. Peak memory drops to one response plus the one arriving. `getMaxPullBatchBytes()` and `estimatePullResponseBytes()` are gone. Over loopback, the pull phase went from 7.8 s to 5.3 s, and the client was initialized after 10.5 s instead of 13.5 s. Applying per response without `onSent` alone gave 12.9 s. The pull specs fail against the batched loop (chunks applied with the cursor of an earlier one) and against a loop that applies before the request is sent; the provider specs fail without the callback. Assisted-by: Claude Code (Claude Opus 5.5)
A CPU profile of a sync server answering an initial sync of a 2 GB database put 0.8 s of its 2.4 s of work in `getEntityChangeRow()`, which ran one `SELECT` per entity change, about 200,000 of them, and read the full content of every blob over the stub limit only to replace it with an empty string: 3,200 blobs, 1.6 GB, for a client that downloads them later through `GET /api/sync/blobs/:blobId`. `getEntityChangeRecords()` now reads the rows of each table at once with `IN (SELECT value FROM json_each(?))`, as the OCR search already does, and leaves binary blob content over the limit out of that query, since `LENGTH()` gets a blob's size without loading it. Such a blob is stubbed, or, without a limit (the push path, older clients), its content is read alone once its record is reached, so a list of large blobs is never held at once. Text content is always read: only its encoded size compares with the limit. Reading every synced row of that database took 830 ms one row at a time, 490 ms with the stubbed content left out, and 350 ms batched as well. In a traced sync over loopback, the server's time per pull went from 68 ms to 55 ms on average and the pull phase from 5.25 s to 5.07 s. The specs fail against the per-row reads: five `getRow` calls for five changes, and the content of a stubbed binary blob read. The stub spec checks each read as it returns, since the record is built by changing the row that was read. Assisted-by: Claude Code (Claude Opus 5.5)
`loadEntityRows()` read every row of a batch of up to 1,000 changes before `getEntityChangeRecords()` applied the 8 MB response cap, with the content of every blob up to the client's stub limit. For a mobile client that limit is 20 MB, so one pull of a range of attachments could hold gigabytes on the sync server to send 8 MB, and content past the cap was read again by the next pull. A change of an unknown entity also threw before any record was built, even past the cap, and a limit of 0 read every blob with a query of its own. The batch query now leaves out all blob content and reads each blob's size instead: `LENGTH()` of binary content, which SQLite answers without loading it, or of the UTF-8 bytes of text. The record loop decides stubs and where the response ends from those sizes, exactly as the per-row loop did, including the record that crosses the cap, and one more query reads the content of only the blobs in the response. A table without a known primary key is skipped by the batch query, so its change throws once it is reached, and 0 means no limit throughout. Text blobs over the limit are now stubbed without being read too; which blobs are stubbed is unchanged. The column list of `blobs` is read with each query instead of once per process, the changes are grouped without copying each table's list per change, and no marker is written onto the rows. A traced initial sync of a 2 GB database shows no change: 52 ms per pull on the server and a 5.06 s pull phase. The specs for content past the cap, an unknown entity past the cap and a limit of 0 each failed before the change. Assisted-by: Claude Code (Claude Opus 5.5)
Express hashes every 2xx response body with SHA-1 for its ETag unless the response already has one. A CPU profile of a sync server serving an initial sync of a 2 GB database spent 674 ms there for the 1.6 GB of `GET /api/sync/blobs/:blobId`, an ETag no sync client reads. A blobId is the hash of the blob's content, so the route sends it as the ETag and Express skips the hash; a profiled trace shows no SHA-1 time left under `getBlob()`. It is weak, as the compression middleware sends the same header for every encoding. Pull responses still get Express's ETag, about 90 ms over the same sync: the setting is per app, and turning it off would also end the revalidation the client's own API requests can answer with a 304. Assisted-by: Claude Code (Claude Opus 5.5)
`NodeRequestProvider` buffered a compressed response and decoded it with `brotliDecompressSync()` or `gunzipSync()` once it had ended, blocking the event loop for each body. A traced initial sync of a 2 GB database spent 2.3 s of the client's main thread there, most of it during the blob downloads that run while the user already works. Each chunk now goes into a `zlib` decoder stream as it arrives, so the decoding runs on libuv's thread pool and overlaps the transfer. A corrupt stream rejects through the decoder's `error` event, and an unknown encoding is refused once the headers arrive. The next trace shows no decompression left on the main thread. This reaches desktop with a sync proxy and a server syncing with another: without a proxy, desktop syncs through `electron.net`, and standalone and mobile through `fetch()`, which decode outside JS. The spec fails against the buffered decoding, which calls the synchronous decoders. Assisted-by: Claude Code (Claude Opus 5.5)
After every committed transaction, `sendTransactionEntityChangesToAllClients()` read the changed entity changes again, filled in their rows and serialized them into one `frontend-update` message. During an initial sync, that ran for every pulled chunk: 0.4 s of the client's main thread for a 2 GB database, for a message no page could use. Until the first sync converges, the database is not initialized, so no page holding froca is loaded, and one that loads afterwards reads the database. The update is now skipped while `isDbInitialized()` is false. Its two queries run only after a transaction that changed entities, not for the ping an empty one sends. A traced sync of that database spends 1-2 ms there instead. The connected client count would not have served: the setup window of desktop counts as a client. The spec fails against the unconditional build, which reads the entity changes. Assisted-by: Claude Code (Claude Opus 5.5)
`updateEntities()` ran two queries for every pulled change: one for any entity change carrying its `changeId`, to skip a change already applied, and one for the local entity change of the same entity, for the conflict check. Replaying the writes of an initial sync of a 2 GB database put the two at 0.28 s of a 3 s apply. The local entity change is now read once and serves both. A change ID belongs to one change of one entity, and an entity has a single row in `entity_changes`, so an applied change can only be on that row; when the row has moved on to a newer local change, both versions of the check fall through to the conflict resolution, where the local change wins. A traced sync of that database converges with both content hash checks passing. The spec fails against the two lookups. Its first version gave the pulled change no `changeId`, which skipped the first lookup, and passed against them. Assisted-by: Claude Code (Claude Opus 5.5)
Blob content under the deferral threshold travels inline in a pull response, base64-encoded. On a 2 GB database that is 112 MB in 30,931 blobs, and 83% of those bytes are valid UTF-8, mostly the HTML of text notes and their revisions, which base64 inflates by a third and hides from brotli. A client now asks for `contentAsText=1` on each pull, and the server sends blob content that is valid UTF-8 as a JSON string, marking the record with `contentEncoding: "utf8"`; other content stays base64. A strict decoder that keeps a byte order mark decides, so encoding the text again on the client gives back the server's bytes and the content hashes match. The marker sits on the record rather than the row, since the receiving side refuses a row with a column its table lacks, and the client encodes the text into the same reused buffer the base64 path decodes into. A server that does not know the parameter keeps sending base64, and an older client never asks, so mixed versions sync as before. Pushes are unchanged. A traced initial sync of that database over loopback went from 61.1 to 52.4 MB on the wire and from 241.8 to 215.0 MB of JSON, in 22 pulls instead of 25; the pull phase went from 4.61 to 4.33 s and both content hash checks passed. A binary format was considered: a stand-in of the same JSON followed by raw bytes measured the same 14%, but would need a new dependency, a second protocol on both sides, and base64 again over the mobile request bridge, which carries strings. The specs for the server's choice of encoding, the route's opt-in, the client's request and the stored bytes each failed first. Assisted-by: Claude Code (Claude Opus 5.5)
`checkContentHash()` sent `GET /api/sync/check` and computed the local content hashes only once the answer had arrived, so the first check after an initial sync of a 2 GB database spent 168 ms on the server and then 132 ms on the client, one after the other. Once the request is sent, the client now calls `getEntityHashes()`, whose result is cached by a fingerprint of `entity_changes`, and `checkContentHashes()` finds it there when the answer arrives. The check of that sync went from 330 ms to 197 ms after its request. The sync specs now mock `getEntityHashes()` along with `checkContentHashes()`: computing the hashes runs the unused-blob sweep, which erased the stubs the deferred-blob specs insert. The spec fails when the hashes are computed after the answer. Assisted-by: Claude Code (Claude Opus 5.5)
A deferred blob whose download fails or stalls is skipped and the pass goes on, so that one bad blob cannot hold back the rest. A server answering every blob with an error, such as a proxy returning 502 while the server behind it is down, was therefore asked for each of them: 3,240 failing requests for a 2 GB database. A pass now stops after `DEFERRED_BLOB_MAX_CONSECUTIVE_FAILURES`, 16, failures in a row, and the remaining blobs stay stubs for the next pass; a successful download resets the count. 16 is four times the downloads in flight, so a wave of parallel failures alone does not stop the pass. The spec fails without the guard, with every blob requested, and without the reset, when every other download fails. Assisted-by: Claude Code (Claude Opus 5.5)
The setup page of a desktop synced from a server now opens the app once the notes are synchronized, while images and files over 32 KB keep downloading in the background. The Synchronization page said the redirect came once synchronization was complete, and now says what a note shows until its content has arrived. Assisted-by: Claude Code (Claude Opus 5.5)
|
🖥️ App preview is ready! 🔗 Preview URL: https://pr-12887.trilium-app.pages.dev ✅ All checks passed This preview will be updated automatically with new commits. |
|
📚 Documentation preview is ready! 🔗 Preview URL: https://pr-12887.trilium-docs.pages.dev ✅ All checks passed This preview will be updated automatically with new commits. |
Bundle ReportChanges will increase total bundle size by 22.81kB (0.02%) ⬆️. This is within the configured threshold ✅ Detailed changes
Affected Assets, Files, and Routes:view changes for bundle: standalone-esmAssets Changed:
view changes for bundle: client-esmAssets Changed:
Files in
Files in
|
[High impact] The PR changes shared sync behavior across clients and servers. The shared decoding requirement must be satisfied before merging; no new behavioral defect was established.
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
`ExecOpts.body` took a string or an object to serialize as JSON, so binary content could only travel as base64 inside JSON. A `Uint8Array` body is now sent as is with `Content-Type: application/octet-stream` by `NodeRequestProvider` (Node and Electron) and by the standalone `fetch()` provider. The native request bridge of the mobile app carries only strings, so `BridgedRequestProvider` refuses a byte body instead of corrupting it; callers check for that before sending one. Assisted-by: Claude Code (Claude Opus 5.5)
A push sent every blob inline, base64 encoded inside the JSON of `PUT /api/sync/update`. V8 caps a string at 536,870,888 characters in Node 24 and Electron 45 alike, so `encodeBase64()` throws for a blob of about 384 MiB (402,653,167 bytes) or more, before any paging. The push then fails on every sync, and since `lastSyncedPush` never moves past that batch, no later local change reaches the server. The server now announces `blobUploads: true` at login. A client that sees it, and has no blob size limit, leaves the content of blobs over `DEFERRED_BLOB_THRESHOLD` (32 KB) out of the pushed record, marks it `contentEncoding: "uploaded"`, and first sends the bytes in `PAGE_SIZE` pages to the new `PUT /api/sync/blobs/:blobId`. The route keeps the pages in memory, in order, until the push that names the blob; `update()` then swaps the content into the record before `updateEntities()`, so conflict handling is unchanged. A push naming content that never arrived or arrived incomplete is refused with a validation error and retried on the next sync, upload included; content no push names within 20 minutes is dropped with the stale partial requests. The pushed records' 8 MB cap still counts the uploaded bytes, which bounds what the server holds per push. Writing each page straight into the blob row was rejected for now: it would write a row no entity change describes yet, which the content check and `eraseUnusedBlobs()` would have to learn to skip. An older server, and the mobile app (blob size limit, string-only bridge), keep receiving inline pushes. End to end, a 400 MiB attachment added to a client pushed in 420 pages and 1.7 s, and the server's copy had the same SHA-256. Assisted-by: Claude Code (Claude Opus 5.5)
|
@FliegendeWurst , this PR changes a bit the sync protocol but it doesn't introduce any breaking changes or a change in the sync protocol. More specifically, it allows binary blob streaming for large files instead of the base 64 mechanism. |
Every sync ended with `GET /api/sync/check`, so an idle client asked the sync server to hash its entity changes every minute, and the second sync that follows an initial setup did it again right after the first had verified everything. After a check finds no difference, `checkContentHash()` now records the sync server's address and instance ID, its highest synced entity change ID, and this instance's push and pull cursors. A later sync that finds the same state, with the server's ID taken from login, pushed nothing, pulled nothing and found nothing new on the server, so it skips the check. A check that finds a difference clears the record, so a divergence sync cannot repair is still checked and reported on every sync; the record lives in memory, so the first sync after a restart always checks. An idle instance therefore compares hashes only when something changes or after a restart, rather than every minute. A divergence does not appear without an entity change, so the skipped checks could not find anything the last one had not. Assisted-by: Claude Code (Claude Opus 5.5)
`downloadDeferredBlobs()` kept every blob the server answered 404 for in `unavailableBlobIds` for the life of the process. A server that is itself a desktop still downloading its own deferred blobs answers 404 for a stub, then fills it without an entity change, so the client never asked again until it restarted. The 404 is now remembered with its time, and the blob is asked for again after `DEFERRED_BLOB_RETRY_DELAY` (10 minutes). Retrying on every pass was rejected: a peer that only holds stubs, such as a device with a blob size limit, would be asked for each of them once a minute. The write of a downloaded blob resumes after a network wait, so in standalone it could be folded into an import's open transaction and rolled back with it while counted as downloaded. It now goes through `whenDatabaseFree()`, as other such writes do. The pull's own apply has the same exposure, as it already did before this branch, and is left as is. Also: - `readBlobContents()` walks the records it was given and reads their content with `getMap()`, which drops a branch no input could reach. - `uploadBlobContents()` no longer uploads empty content for a blob row that disappeared during the push; the push fails and is retried on the next sync instead. - Specs cover uploading text content as its UTF-8 bytes and uploads taking the same proxy choice as the push. Assisted-by: Claude Code (Claude Opus 5.5)
`--out` removed whatever directory it was given before writing a trace, so pointing it at a working directory, or at one holding the `--from-db` database, deleted it. The tool now writes a `.sync-trace` marker into its output and only replaces a directory that carries one; it refuses any other non-empty directory, and one that holds the database to trace. The viewer's step descriptions for a pull and a deferred blob still described the batched apply and one download at a time; they now describe the per-response apply and four downloads at a time, smallest first. Assisted-by: Claude Code (Claude Opus 5.5)
The server and standalone CI runs failed their 100 % coverage gates. Specs now cover a stalled request that only has `destroy()`, a `blob-sizes` request without a body, pulled text over the decode pool, a fetch response without a body stream, and, for blob uploads, a page that does not follow the previous one and an upload that outlives the cleanup of stale ones. `isStandalone()` in core's utils lost its only caller when the pull batch budget went, and is removed. The helpers added to the Node request provider move below `NodeRequestProvider`, and the `isWorthCompressing()` comment keeps the rule without the measurements behind it. Assisted-by: Claude Code (Claude Opus 5.5)
When a content check finds a blob sector diverged, `addEntityChangesForSector()` re-queues every blob of the sector, sync stubs included: the blobs a pull left empty, which the mobile app keeps for content over its size limit and a desktop keeps until its deferred download fills them. The push sent such a stub with empty content under its original hash and `utcDateChanged`, and `updateNormalEntity()` takes an equal date as the remote being newer, so the sync server replaced the full blob with nothing. The hashes still matched, so no later check noticed, and every other client then pulled the empty blob. Both ends now refuse it. `pushChanges()` leaves sync stubs out of a push, as `requeueOwnBlobIfRemoteLacksIt()` already did, and moves the cursor past them. `updateNormalEntity()` keeps the local content of a blob that an incoming empty row would replace: a `blobId` other than `EMPTY_BLOB_ID` never names empty content, so such a row is always a peer's stub. The receiving check also protects a sync server from older mobile clients, and a new blob that arrives as a stub is still stored as one. Assisted-by: Claude Code (Claude Opus 5.5)
A note whose blob a pull left out as a stub showed the "open on server" placeholder until the background pass reached it, and never refreshed when it did: filling a stub writes no entity change, so nothing told the client. On the mobile app, which keeps blobs over `syncMaxBlobContentSize` as stubs for good, the placeholder stayed. Opening such a note now asks `POST /api/sync/download-blob/:blobId` to fetch it at once; `BlobStub` shows that it is downloading, and offers to try again or to open the note on the sync server when the download fails. `downloadBlobNow()` starts the download alongside the background pass rather than reordering it: `downloadDeferredBlob()` keeps one download per blob in flight, which the pass shares, and skips a blob that is no longer a stub. It reuses the session of the last converged sync, and logs in when there is none or the server answers 401. Mobile downloads on demand only; the pass stays off there. Every filled stub, from either path, is announced with a `blob-download` message, on which `froca_updater.processDownloadedBlob()` drops the cached blobs and reloads the content of the notes holding it, so a note on its placeholder shows the content when it arrives. The native request bridge refused byte responses; it now asks the native side for a binary body, which arrives as base64, as image downloads already do, and bounds a request that has only an idle timeout by that timeout, as the bridge reports no progress. On mobile the whole blob is held as base64 while it downloads, which is accepted for a download the user asked for. The `blob_stub.not_synced` message is reworded, since a desktop now shows it too, when its sync server cannot provide the content. Assisted-by: Claude Code (Claude Opus 5.5)
The sync server held content uploaded through `PUT /api/sync/blobs/:blobId` in `uploadedBlobs`, keyed by `blobId`. A blob ID is a hash of the content, so two devices pushing the same large file shared one entry: the first page of one upload replaced the other's half-finished upload, whose next page then failed the `requestId` check, and one device's push deleted content the other's push still needed. Either way the other device's sync run failed. `uploadedBlobs` is now keyed by the upload's `requestId` and records the blob it carries. `uploadBlobContents()` sets that ID as the record's new `uploadId`, and `update()` uses only the upload it names, refusing one made for a different blob. Blob uploads have not been released, so no older client or server needs the `blobId` key. Assisted-by: Claude Code (Claude Opus 5.5)
The `BlobStub` spec never set `syncServerHost`, so the "Open on server" button and its `window.open()` call went untested. The new case sets a host with trailing slashes and checks the URL the button opens; every case now starts with the option empty. Assisted-by: Claude Code (Claude Opus 5.5)
The coverage gate failed on branches no caller can take, so the code loses them instead of gaining specs that fake them. - The pull and the content check each sent a request, waited until it was written and kept the response, with a placeholder `markSent` that was always replaced and their own rejection handlers. `sendAhead()` now does this once, on `deferred()` from commons. - `createContentDecoder()` threw only its own `Error` for an encoding it cannot decode, which the caller caught to read `e.message` or `String(e)`. It now returns `undefined` for that case; the rejection message is unchanged. - `update()` checked `record.uploadId` twice; it reads it once. Assisted-by: Claude Code (Claude Opus 5.5)
The server and standalone coverage gates failed on sync branches that no spec reached: - deferred blob downloads that fail with a value that is not an `Error`, and a `blob-sizes` request that answers nothing; the fake sync server can now produce both - a blob whose content is NULL, pushed as is past a size limit and applied over local content, as only empty content is a stub - a push that marks a blob uploaded but names no upload - a client that decodes the response body itself, so Node's request provider asks for no encoding and passes the body through - a JSON body read by standalone's request provider under an idle timeout Assisted-by: Claude Code (Claude Opus 5.5)
| }, opts.idleTimeout); | ||
| }; | ||
| const readText = async (response: Response) => opts.idleTimeout | ||
| ? new TextDecoder().decode(await readBody(response, controller.signal, restartIdleTimer)) |
There was a problem hiding this comment.
Decoding bypasses the shared helper
readText() converts bytes with a new TextDecoder, but the repository guide requires binary conversions to go through binary.ts. Use decodeUtf8() here to avoid maintaining a separate decoding path. This repository requirement must be satisfied before merging.
Context Used: CLAUDE.md (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Setting up sync from a server with a large knowledge base now gets the user to their notes in a fraction of the time, and the images and files follow in the background.
Measured with the new
pnpm dev:sync-trace --from-dbon a 2 GB database (202,350 entity changes, 1.85 GB of blob content), over loopback:Over a simulated 100 Mbit/s link with 50 ms of latency, the client was usable after 15 s instead of 28 s at the point compression landed, and all content was present after 133 s instead of 336 s; the pull-side changes after that point were measured over loopback and a simulated gigabit LAN.
No sync version bump: every new behaviour is requested by the client (
deferBlobsOver,contentAsText,Accept-Encoding), and an old server ignores the request and answers as before, while an old client never asks.Large blobs download after the pull
DEFERRED_BLOB_THRESHOLD) out withdeferBlobsOver, as stubs exactly like the mobilemaxBlobContentSizelimit makes, with the entity change and its hash untouched, so the content check passes as before. After a sync converges,downloadDeferredBlobs()fetches each stub from the newGET /api/sync/blobs/:blobIdasapplication/octet-streamand writes it into the stub row. The stubs are the work list, so an interrupted download resumes after a restart; a blob never changes under itsblobId, so no entity change is written. The download runs outside the sync mutex. The 32 KB threshold won a matrix against higher ones, even with compression: 256 KB would leave 465 MB on the wire before the client is usable.DEFERRED_BLOB_CONCURRENCY): one at a time, each blob waited a round trip; at 100 Mbit/s and 50 ms the downloads went from 307.6 s to 143.9 s, with the link saturated.POST /api/sync/blob-sizesreports (LENGTH()reads them without loading content), so most content arrives early; on this database the largest 90 of 3,240 blobs carry half the bytes.DEFERRED_BLOB_MAX_CONSECUTIVE_FAILURES), so a server answering 502 to everything is not asked 3,240 times. Downloads are bounded by an idle timeout rather than a total one, so a large blob on a slow but working link finishes.application/octet-stream; it is now kept off PNG (2 % saving), protected and ownerless blobs withCache-Control: no-transform. PDF, MP4 and JPEG still compress by 14-29 %, which is why ZIP export's list of already-compressed types was rejected.W/"<blobId>", so Express no longer SHA-1-hashes 1.6 GB of bodies (674 ms of server CPU per initial sync).Pulls
ExecOpts.onSentreports. Committing per response instead of per batch measured about 80 ms over the whole sync. Pull phase: 7.8 s to 5.3 s.getEntityChangeRecords()read one row per change and the full content of every blob it then stubbed (1.6 GB). It now reads each table's rows in one query without blob content, decides stubs and the 8 MB response cap from the blobs' sizes exactly as before, and reads only the content of the blobs in the response, which also bounds the server's memory for a mobile client's 20 MB limit.contentAsText=1, the server sends such content as a JSON string markedcontentEncoding: "utf8"on the record; a strict decoder that keeps a byte order mark decides, so the client's bytes and hashes match the server's. 14 % fewer bytes on the wire, the same saving a binary format measured, without a new dependency or a second protocol, and over the mobile request bridge too.frontend-updatemessage is built while the database is not initialized, as no page holding froca exists yet (0.4 s per initial sync).Requests
RequestStatusErrorandRequestStallErrorlet a caller tell an error status from a stalled response;ExecOpts.idleTimeout,responseType: "bytes"andonSentare implemented by the Node/Electron and fetch providers.NodeRequestProvidernow asks forbr, gzipand decodes the body on the thread pool as it arrives. This reaches a desktop with a sync proxy and a server syncing with another;electron.netandfetch()already negotiated and decoded compression themselves.Tooling
pnpm dev:sync-tracerecords a full sync between two local instances behind a recording proxy and writes a self-contained viewer:--from-dbserves a snapshot of an existing database (read through SQLite's backup API, with its sync server and password replaced),--throttlesimulates a link,--compressmeasures an encoding end to end, and--cpu-profprofiles both instances. Documented in the Developer Guide under Synchronisation.Known follow-ups