Skip to content

perf(sync): get to the notes sooner on a large initial sync - #12887

Merged
eliandoran merged 35 commits into
mainfrom
feature/sync_overhaul
Nov 30, 2026
Merged

eliandoran merged 35 commits into
mainfrom
feature/sync_overhaul

Conversation

@eliandoran

Copy link
Copy Markdown
Contributor

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-db on a 2 GB database (202,350 entity changes, 1.85 GB of blob content), over loopback:

before after
pull requests 200, 2.56 GB 22, 52 MB on the wire (215 MB JSON)
notes usable after the whole download about 5 s after setup starts
large blobs inline, base64 3,240 raw downloads in the background

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 blobs. Pulls leave blobs over 32 KB (DEFERRED_BLOB_THRESHOLD) out with deferBlobsOver, as stubs exactly like the mobile maxBlobContentSize limit 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 new GET /api/sync/blobs/:blobId as application/octet-stream and 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 its blobId, 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.
  • Four at a time (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.
  • Smallest first, by the sizes the new POST /api/sync/blob-sizes reports (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.
  • Failures. A blob the server answers with an error status, or whose download stalls, is skipped and stays a stub for the next pass; a connection-level error ends the pass, as do 16 failures in a row (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.
  • Compression. The middleware compresses application/octet-stream; it is now kept off PNG (2 % saving), protected and ownerless blobs with Cache-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.
  • ETag. The blob route sends W/"<blobId>", so Express no longer SHA-1-hashes 1.6 GB of bodies (674 ms of server CPU per initial sync).

Pulls

  • Apply while the next chunk downloads. The pull fired its prefetch just before applying a 32 MB batch, but on Node and Electron that request only left once the synchronous apply had ended, so the server prepared nothing meanwhile. Each response is now applied in its own transaction once the next request is sent, which the new ExecOpts.onSent reports. Committing per response instead of per batch measured about 80 ms over the whole sync. Pull phase: 7.8 s to 5.3 s.
  • Batched row reads. 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.
  • Text content as text. 83 % of the inline blob bytes are valid UTF-8, mostly note HTML. With contentAsText=1, the server sends such content as a JSON string marked contentEncoding: "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.
  • Fewer queries on the client. One local lookup per pulled change instead of two; no frontend-update message is built while the database is not initialized, as no page holding froca exists yet (0.4 s per initial sync).
  • Content check. The client hashes its own content while the server hashes its own.

Requests

  • RequestStatusError and RequestStallError let a caller tell an error status from a stalled response; ExecOpts.idleTimeout, responseType: "bytes" and onSent are implemented by the Node/Electron and fetch providers.
  • NodeRequestProvider now asks for br, gzip and 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.net and fetch() already negotiated and decoded compression themselves.

Tooling

pnpm dev:sync-trace records a full sync between two local instances behind a recording proxy and writes a self-contained viewer: --from-db serves a snapshot of an existing database (read through SQLite's backup API, with its sync server and password replaced), --throttle simulates a link, --compress measures an encoding end to end, and --cpu-prof profiles both instances. Documented in the Developer Guide under Synchronisation.

Known follow-ups

  • While a deferred blob downloads, its note shows the mobile placeholder ("too large to sync to this device") and does not refresh when the content arrives.
  • Pushes still send blob content inline as base64, so a large attachment created locally uploads the way large downloads used to.

`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)
@github-actions

Copy link
Copy Markdown
Contributor

🖥️ App preview is ready!

🔗 Preview URL: https://pr-12887.trilium-app.pages.dev
📖 Production URL: https://app.triliumnotes.org

✅ All checks passed

This preview will be updated automatically with new commits.

@github-actions

Copy link
Copy Markdown
Contributor

📚 Documentation preview is ready!

🔗 Preview URL: https://pr-12887.trilium-docs.pages.dev
📖 Production URL: https://docs.triliumnotes.org

✅ All checks passed

This preview will be updated automatically with new commits.

@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Bundle Report

Changes will increase total bundle size by 22.81kB (0.02%) ⬆️. This is within the configured threshold ✅

Detailed changes
Bundle name Size Change
standalone-esm 55.25MB 19.04kB (0.03%) ⬆️
client-esm 44.54MB 3.77kB (0.01%) ⬆️

Affected Assets, Files, and Routes:

view changes for bundle: standalone-esm

Assets Changed:

Asset Name Size Change Total Size Change (%)
assets/src-*.js -2.32MB 1.66kB -99.93%
assets/src-*.js 97.64kB 99.3kB 5896.14% ⚠️
assets/src-*.js 2.23MB 2.33MB 2244.35% ⚠️
src/src-*.js -9 bytes 257 bytes -3.38%
src/src-*.js -64 bytes 193 bytes -24.9%
src/src-*.js 73 bytes 266 bytes 37.82% ⚠️
assets/base_provider-*.js 32 bytes 305.38kB 0.01%
assets/dist-*.js -25.2kB 3.79kB -86.92%
assets/dist-*.js -14.79kB 3.67kB -80.1%
assets/dist-*.js 90.74kB 98.58kB 1157.6% ⚠️
assets/dist-*.js -81.48kB 3.84kB -95.5%
assets/dist-*.js -12.86kB 2.61kB -83.13%
assets/dist-*.js 23.31kB 27.26kB 590.38% ⚠️
assets/dist-*.js 40 bytes 3.94kB 1.03%
assets/dist-*.js 14.48kB 18.47kB 363.27% ⚠️
assets/dist-*.js -114 bytes 3.75kB -2.95%
assets/dist-*.js -40.38kB 4.06kB -90.87%
assets/dist-*.js 181 bytes 3.88kB 4.89%
assets/dist-*.js 68.29kB 71.03kB 2486.78% ⚠️
assets/dist-*.js 986 bytes 3.8kB 34.99% ⚠️
assets/dist-*.js -13.67kB 13.59kB -50.14%
assets/dist-*.js -103 bytes 3.7kB -2.71%
assets/dist-*.js 14.6kB 18.39kB 385.1% ⚠️
assets/dist-*.js -144.21kB 40.48kB -78.08%
assets/dist-*.js 19.5kB 23.34kB 507.18% ⚠️
assets/dist-*.js 228.1kB 232.03kB 5811.59% ⚠️
assets/dist-*.js 1.37kB 5.33kB 34.57% ⚠️
assets/dist-*.js 143.85kB 147.52kB 3913.17% ⚠️
assets/dist-*.js -225.84kB 3.99kB -98.26%
assets/dist-*.js 215 bytes 4.21kB 5.39% ⚠️
assets/dist-*.js -94.63kB 3.95kB -95.99%
assets/dist-*.js 12.47kB 27.07kB 85.47% ⚠️
assets/dist-*.js -36.57kB 3.91kB -90.34%
assets/dist-*.js 80 bytes 3.86kB 2.12%
assets/dist-*.js 181.02kB 184.68kB 4948.69% ⚠️
assets/dist-*.js 25.16kB 28.99kB 657.24% ⚠️
assets/dist-*.js 17.33kB 21.21kB 447.07% ⚠️
assets/dist-*.js -8.21kB 3.68kB -69.08%
assets/dist-*.js -100.41kB 3.78kB -96.37%
assets/dist-*.js 41.52kB 45.4kB 1069.45% ⚠️
assets/dist-*.js -23.56kB 7.84kB -75.03%
assets/dist-*.js -14.57kB 3.83kB -79.19%
assets/dist-*.js -181 bytes 3.88kB -4.46%
assets/dist-*.js -13.02kB 3.94kB -76.76%
assets/dist-*.js -15 bytes 3.9kB -0.38%
assets/dist-*.js 28.72kB 32.66kB 729.12% ⚠️
assets/dist-*.js -19.64kB 3.71kB -84.13%
assets/dist-*.js 235 bytes 3.95kB 6.33% ⚠️
assets/dist-*.js -4.96kB 3.85kB -56.32%
assets/dist-*.js -18.35kB 21.48kB -46.08%
assets/dist-*.js -41.74kB 3.66kB -91.94%
assets/dist-*.js -9.68kB 3.91kB -71.2%
assets/dist-*.js 136 bytes 2.75kB 5.21% ⚠️
assets/dist-*.js 12.89kB 16.57kB 350.95% ⚠️
assets/dist-*.js 285 bytes 4.03kB 7.61% ⚠️
assets/dist-*.js -17.49kB 3.72kB -82.46%
assets/dist-*.js 7.68kB 11.89kB 182.58% ⚠️
assets/dist-*.js -9.89kB 11.59kB -46.03%
assets/dist-*.js -212.93kB 31.4kB -87.15%
assets/dist-*.js -40.78kB 244.33kB -14.3%
assets/dist-*.js -6 bytes 3.71kB -0.16%
assets/dist-*.js -1.12kB 2.82kB -28.53%
assets/dist-*.js 281.16kB 285.11kB 7118.03% ⚠️
assets/dist-*.js -107 bytes 3.92kB -2.65%
assets/dist-*.js -132.93kB 14.59kB -90.11%
assets/dist-*.js 39.11kB 44.44kB 733.93% ⚠️
assets/dist-*.js 14.3kB 85.33kB 20.13% ⚠️
assets/dist-*.js 3.88kB 15.47kB 33.44% ⚠️
assets/dist-*.js 281 bytes 3.99kB 7.58% ⚠️
assets/dist-*.js 87.62kB 104.19kB 528.86% ⚠️
assets/dist-*.js 13.05kB 16.96kB 334.06% ⚠️
assets/dist-*.js -18.2kB 8.82kB -67.37%
assets/dist-*.js 35.69kB 39.83kB 862.13% ⚠️
assets/dist-*.js 109 bytes 3.96kB 2.83%
assets/dist-*.js -28.52kB 4.14kB -87.32%
src/dist-*.js 2.17kB 235.31kB 0.93%
src/dist-*.js 11 bytes 10.11kB 0.11%
src/dist-*.js 54 bytes 26.95kB 0.2%
src/dist-*.js -18 bytes 42 bytes -30.0%
src/dist-*.js 1 bytes 42 bytes 2.44%
src/dist-*.js 84 bytes 67.88kB 0.12%
src/dist-*.js 18 bytes 60 bytes 42.86% ⚠️
src/dist-*.js -1 bytes 41 bytes -2.38%
assets/mathematica-*.js -107.96kB 1.98kB -98.2%
assets/mathematica-*.js 107.96kB 109.93kB 5460.65% ⚠️
assets/share-*.js 21 bytes 98.3kB 0.02%
assets/code_preview-*.js 82 bytes 81.07kB 0.1%
src/i18next-*.js 158 bytes 50.34kB 0.31%
assets/sql-*.js -31.34kB 5.67kB -84.67%
assets/sql-*.js 31.34kB 37.01kB 552.27% ⚠️
src/config-*.js -79 bytes 34.13kB -0.23%
assets/tools-*.js 32 bytes 29.99kB 0.11%
assets/css-*.js -12.76kB 12.2kB -51.11%
assets/css-*.js 12.76kB 24.96kB 104.56% ⚠️
assets/stylus-*.js -11.21kB 12.53kB -47.22%
assets/stylus-*.js 11.21kB 23.74kB 89.46% ⚠️
assets/javascript-*.js 10.61kB 17.04kB 164.95% ⚠️
assets/javascript-*.js -10.61kB 6.43kB -62.26%
src/ws-*.js 516 bytes 14.24kB 3.76%
src/MobileNoteNavigator-*.js 91 bytes 14.06kB 0.65%
src/StatusBar-*.js 72 bytes 13.89kB 0.52%
src/mobile-*.js 28 bytes 12.7kB 0.22%
assets/epub_pass-*.js 31 bytes 11.96kB 0.26%
assets/crypto_provider-*.js 27 bytes 11.41kB 0.24%
assets/zip_export_provider_factory-*.js 32 bytes 10.58kB 0.3%
assets/gherkin-*.js 9.3kB 10.22kB 1003.89% ⚠️
assets/gherkin-*.js -9.3kB 926 bytes -90.94%
assets/clojure-*.js 5.33kB 9.52kB 126.98% ⚠️
assets/clojure-*.js -5.33kB 4.2kB -55.94%
assets/verilog-*.js 3.4kB 8.6kB 65.41% ⚠️
assets/verilog-*.js -3.4kB 5.2kB -39.54%
assets/swift-*.js 4.32kB 8.19kB 111.63% ⚠️
assets/swift-*.js -4.32kB 3.87kB -52.75%
assets/haxe-*.js 5.77kB 7.93kB 265.96% ⚠️
assets/haxe-*.js -5.77kB 2.17kB -72.67%
assets/powershell-*.js -3.39kB 4.42kB -43.42%
assets/powershell-*.js 3.39kB 7.8kB 76.74% ⚠️
assets/web_search-*.js 32 bytes 7.6kB 0.42%
assets/scheme-*.js -3.17kB 3.34kB -48.64%
assets/scheme-*.js 3.17kB 6.51kB 94.71% ⚠️
assets/python-*.js 3.0kB 6.42kB 87.88% ⚠️
assets/python-*.js -3.0kB 3.42kB -46.77%
assets/cobol-*.js -2.23kB 4.07kB -35.44%
assets/cobol-*.js 2.23kB 6.31kB 54.89% ⚠️
assets/xquery-*.js 875 bytes 6.25kB 16.26% ⚠️
assets/xquery-*.js -875 bytes 5.38kB -13.99%
assets/zip_records-*.js 32 bytes 6.08kB 0.53%
assets/xml-*.js -3.68kB 1.93kB -65.54%
assets/xml-*.js 3.68kB 5.61kB 190.23% ⚠️
assets/vbscript-*.js 3.96kB 5.61kB 240.15% ⚠️
assets/vbscript-*.js -3.96kB 1.65kB -70.6%
assets/julia-*.js -1.81kB 3.59kB -33.53%
assets/julia-*.js 1.81kB 5.4kB 50.45% ⚠️
assets/crystal-*.js -1.47kB 3.65kB -28.77%
assets/crystal-*.js 1.47kB 5.12kB 40.38% ⚠️
assets/livescript-*.js -879 bytes 3.27kB -21.19%
assets/livescript-*.js 879 bytes 4.15kB 26.88% ⚠️
assets/d-*.js 1.28kB 3.77kB 51.47% ⚠️
assets/d-*.js -1.28kB 2.49kB -33.98%
assets/q-*.js -2.58kB 1.19kB -68.41%
assets/q-*.js 2.58kB 3.77kB 216.53% ⚠️
assets/0240__migrate_board_status_to_select-*.js 27 bytes 3.62kB 0.75%
assets/bridged_request_provider-*.js 445 bytes 3.34kB 15.36% ⚠️
assets/cypher-*.js -1.5kB 1.81kB -45.23%
assets/cypher-*.js 1.5kB 3.31kB 82.59% ⚠️
assets/request_provider-*.js 1.05kB 3.03kB 52.62% ⚠️
assets/log_provider-*.js -5 bytes 2.98kB -0.17%
assets/go-*.js 1.31kB 2.82kB 86.9% ⚠️
assets/go-*.js -1.31kB 1.51kB -46.49%
assets/rust-*.js 641 bytes 2.82kB 29.43% ⚠️
assets/rust-*.js -641 bytes 2.18kB -22.74%
assets/request-*.js 197 bytes 2.56kB 8.35% ⚠️
assets/tcl-*.js 671 bytes 2.42kB 38.34% ⚠️
assets/tcl-*.js -671 bytes 1.75kB -27.72%
assets/markdown-*.js -1.79kB 365 bytes -83.05%
assets/markdown-*.js 1.79kB 2.15kB 490.14% ⚠️
assets/smalltalk-*.js -1.41kB 666 bytes -67.95%
assets/smalltalk-*.js 1.41kB 2.08kB 212.01% ⚠️
assets/ebnf-*.js 1.62kB 2.05kB 382.12% ⚠️
assets/ebnf-*.js -1.62kB 425 bytes -79.26%
assets/office_headings-*.js 31 bytes 1.96kB 1.61%
assets/binary-*.js (New) 1.68kB 1.68kB 100.0% 🚀
assets/zh-*.js 32 bytes 1.55kB 2.11%
assets/zh-*.js -32 bytes 1.51kB -2.07%
src/BlobStub-*.js 829 bytes 1.39kB 147.25% ⚠️
src/TextBoxEditor-*.js -131 bytes 937 bytes -12.27%
assets/diff-*.js -275 bytes 370 bytes -42.64%
assets/diff-*.js 275 bytes 645 bytes 74.32% ⚠️
src/BlobStub-*.css 72 bytes 192 bytes 60.0% ⚠️
assets/__vite-*.js -74 bytes 110 bytes -40.22%
assets/__vite-*.js 74 bytes 184 bytes 67.27% ⚠️
view changes for bundle: client-esm

Assets Changed:

Asset Name Size Change Total Size Change (%)
src/editor.desktop-*.js -74 bytes 1.93MB -0.0%
src/script-*.desktop-fUtWQfd8.js (New) 507.64kB 507.64kB 100.0% 🚀
src/launch-*.desktop.mobile-FVKBU0AM.js (New) 396.87kB 396.87kB 100.0% 🚀
src/right-*.desktop-DpOSVoLv.js (New) 171.6kB 171.6kB 100.0% 🚀
src/shell.desktop.mobile.login.setup.set_password.print-*.js 162 bytes 154.78kB 0.1%
src/dist-*.js 6 bytes 48 bytes 14.29% ⚠️
src/dist-*.js 54 bytes 26.98kB 0.2%
src/dist-*.js 11 bytes 10.14kB 0.11%
src/dist-*.js -6 bytes 42 bytes -12.5%
src/shell.desktop.mobile-*.js 1 bytes 121.9kB 0.0%
src/shell.desktop.mobile.setup.print-*.js 520 bytes 85.96kB 0.61%
src/board-*.js -1 bytes 82.04kB -0.0%
src/shell.desktop-*.js 72 bytes 80.34kB 0.09%
src/status-*.desktop_launch-bar.mobile-BKLPEtwf.js (New) 66.95kB 66.95kB 100.0% 🚀
src/shell.desktop.mobile.print-*.js 6 bytes 63.07kB 0.01%
src/status-*.desktop-BILHU6f6.js (New) 62.49kB 62.49kB 100.0% 🚀
src/src-*.js -73 bytes 193 bytes -27.44%
src/src-*.js 74 bytes 266 bytes 38.54% ⚠️
src/src-*.js -1 bytes 192 bytes -0.52%
src/Code-*.js -1 bytes 19.0kB -0.01%
src/revisions-*.js 10 bytes 14.36kB 0.07%
src/MobileNoteNavigator-*.js 91 bytes 13.77kB 0.67%
src/mobile-*.js 28 bytes 12.45kB 0.23%
src/data-*.js -5 bytes 11.28kB -0.04%
src/launch-*.desktop.mobile_shell.setup-BajS4OSZ.js (New) 9.14kB 9.14kB 100.0% 🚀
src/ListOrGridView-*.js 5 bytes 7.42kB 0.07%
src/script-*.desktop_shell.login.setup.set_password-CXf3uLok.js (New) 4.87kB 4.87kB 100.0% 🚀
src/recent_changes-*.js -5 bytes 4.32kB -0.12%
src/script-*.desktop-CCU4pxnM.js (New) 3.9kB 3.9kB 100.0% 🚀
src/shell.desktop.print_launch-*.mobile-sd3WLcbM.js (New) 3.59kB 3.59kB 100.0% 🚀
src/jump_to_note-*.js -5 bytes 2.97kB -0.17%
src/status-*.desktop_shell.login.setup.set_password-ctrnlcKe.js (New) 1.93kB 1.93kB 100.0% 🚀
src/move_to-*.js -5 bytes 1.65kB -0.3%
src/BlobStub-*.js 737 bytes 1.39kB 112.35% ⚠️
src/script-*.desktop_shell.setup-aB_9Uh60.js (New) 1.21kB 1.21kB 100.0% 🚀
src/TextBoxEditor-*.js -156 bytes 977 bytes -13.77%
src/status-*.desktop_launch-bar.mobile_shell.login.setup.set_password-DvMXX60u.js (New) 854 bytes 854 bytes 100.0% 🚀
src/launch-*.desktop.mobile_shell.login.setup.set_password-C3oNAi32.js (New) 789 bytes 789 bytes 100.0% 🚀
src/BlobStub-*.css 72 bytes 192 bytes 60.0% ⚠️
src/script-*.desktop-hbC4m7GK.js (Deleted) -507.64kB 0 bytes -100.0% 🗑️
src/launch-*.desktop.mobile-fzov8ENK.js (Deleted) -394.62kB 0 bytes -100.0% 🗑️
src/right-*.desktop-D1BiWAc9.js (Deleted) -171.6kB 0 bytes -100.0% 🗑️
src/status-*.desktop_launch-bar.mobile-OPgAi0Kf.js (Deleted) -66.96kB 0 bytes -100.0% 🗑️
src/status-*.desktop-DvDPqDsP.js (Deleted) -62.49kB 0 bytes -100.0% 🗑️
src/launch-*.desktop.mobile_shell.setup-aakicP8v.js (Deleted) -9.14kB 0 bytes -100.0% 🗑️
src/script-*.desktop_shell.login.setup.set_password-DeA9GzeD.js (Deleted) -4.87kB 0 bytes -100.0% 🗑️
src/script-*.desktop-C4D5YCgK.js (Deleted) -3.9kB 0 bytes -100.0% 🗑️
src/shell.desktop.print_launch-*.mobile-DZkUWX7j.js (Deleted) -3.59kB 0 bytes -100.0% 🗑️
src/status-*.desktop_shell.login.setup.set_password-DfEJ0Hhm.js (Deleted) -1.93kB 0 bytes -100.0% 🗑️
src/script-*.desktop_shell.setup-sb48kR-2.js (Deleted) -1.21kB 0 bytes -100.0% 🗑️
src/status-*.desktop_launch-bar.mobile_shell.login.setup.set_password-7cVWBoc3.js (Deleted) -854 bytes 0 bytes -100.0% 🗑️
src/launch-*.desktop.mobile_shell.login.setup.set_password-D78q7X6x.js (Deleted) -789 bytes 0 bytes -100.0% 🗑️

Files in src/shell.desktop.mobile.setup.print-*.js:

  • ./src/services/ws.ts → Total Size: 9.75kB

  • ./src/services/froca_updater.ts → Total Size: 10.01kB

Files in src/BlobStub-*.js:

  • ./src/widgets/type_widgets/BlobStub.tsx → Total Size: 1.75kB

  • ./src/widgets/type_widgets/BlobStub.css → Total Size: 0 bytes

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5 · The shared decoding requirement must be satisfied before merging; no new behavioral defect was established.RetriggerView in GreptileConfidence Score: 4/5

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

FindingsFix All in Claude CodeFindings

  1. P2 Decoding bypasses the shared helper ▶

Summary

This PR makes notes available before large files finish syncing.

  • Large blobs download after sync, while their notes become usable sooner.
  • Sync pulls use fewer database reads and overlap downloads with local work.
  • Request providers stream bytes, detect stalled downloads, and decode compressed replies.
  • Large blob pushes send file bytes before the entity change that names them.
  • Developers can record and inspect a sync between local Trilium instances.

One repository requirement remains: use the shared text-decoding helper.

Diagram

sequenceDiagram
    participant Client
    participant Server
    participant Database
    Client->>Server: Pull changes with blob deferral
    Server-->>Client: Notes and blob stubs
    Client->>Server: Request next chunk
    Client->>Database: Apply current chunk
    Client->>Server: Compare content hashes
    Server-->>Client: Matching hashes
    Note over Client: Notes become available
    Client->>Server: Download deferred blobs
    Server-->>Client: Raw bytes
    Client->>Database: Fill stub content
    Note over Client: Notify open pages
Loading

Reviews (5) · Last reviewed commit: "chore(sync): cover the sync paths the co..." · Reviewed by Greptile

Comment thread scripts/sync-trace/sync-trace.mts Resolved
Comment thread apps/server/src/services/request.ts Resolved
Comment thread scripts/sync-trace/viewer.html Resolved
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 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)
@eliandoran

Copy link
Copy Markdown
Contributor Author

@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)
@eliandoran eliandoran added this to the v0.109.0 milestone Nov 29, 2026
@eliandoran
eliandoran marked this pull request as ready for review November 29, 2026 20:53
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 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!

Fix in Claude Code

@eliandoran
eliandoran merged commit 1a18868 into main Nov 30, 2026
30 checks passed
@eliandoran
eliandoran deleted the feature/sync_overhaul branch November 30, 2026 08:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant