Server storage and note services
The server storage layer gives Trilium one durable store for notes, note relationships, content, attachments, revisions, options, and change records. It opens that store through a platform SQL provider, keeps a usable note view in memory, and coordinates backups, restore, cleanup, and note changes so the HTTP server and sync system see consistent state. See Server platform for the wider server lifecycle and Server HTTP API and sharing for the public interfaces that use these services.
Storage model
Relational note state
The database separates a note from the places where it appears. A note stores identity and metadata. A branch connects it to a parent and gives that placement an order. Attributes hold labels and relations. This model allows one note to have more than one parent while preserving one shared note identity.
Content-bearing records point to rows in blobs. Notes, revisions, and attachments can therefore share the same stored content. The database also keeps entity changes so local writes can reach clients and sync peers. The main tables and their links are defined in packages/…/schema.sql.
The server loads live notes, branches, attributes, options, and API tokens into the Becca note view after the database is ready. Becca is the in-memory view used for tree navigation and note work; SQL remains the durable source and is updated through entity services. packages/…/becca_loader.ts• L18-73
References: packages/…/schema.sql• L1-164 packages/…/becca_loader.ts• L31-73 packages/…/bnote.ts• L51-63
Content and blob storage
Note and attachment content is stored separately from metadata and loaded when a caller asks for it. A content write creates or reuses a content blob, points the owning record at it, and records the change. Hash-based blob identity avoids storing the same content more than once when entities can safely share it.
Protected content is encrypted before it is stored and is returned only when a protected session is available. Binary content stays binary. Text content is decoded for note use. OCR text is kept with the blob and follows the same protection boundary as the content from which it came. packages/…/abstract_becca_entity.ts• L143-193 and packages/…/blob.ts• L90-137
References: packages/…/abstract_becca_entity.ts• L143-193 packages/…/abstract_becca_entity.ts• L230-287 packages/…/blob.ts• L10-40
Downloaded resources
The resource service manages large files that support server features, such as models. A registered resource describes its files, source URLs, expected sizes, hashes, license, and attribution. The service reports status and free space, shares progress with clients, and removes installed resources when they are no longer needed. apps/…/resources.ts• L16-54 and apps/…/resources.ts• L157-180
Downloads are stored outside the note database in a resource directory. Each file is accepted only after its size and SHA-256 hash match the definition. Interrupted downloads keep usable partial data for resume, while a changed definition gets a new resource directory. The service writes a notice with source and license information beside each installed resource. apps/…/resources.ts• L120-127 and apps/…/resources.ts• L234-293
Resource and note-related downloads use shared request facilities that validate outbound addresses before they connect. The resource-facing request path also limits the response data that a caller can consume, so remote content cannot grow without bound in server memory. apps/…/request.ts• L204-218 and apps/…/safe_fetch.ts• L212-258
Resource downloads also handle stalled connections and incomplete range responses. The service keeps valid partial bytes for a later attempt, discards bytes when the requested range cannot be trusted, and reports progress and terminal status to clients. The resource tests cover verification, cancellation, resume, replacement, and cleanup of unregistered files. apps/…/resources.spec.ts• L80-180 and apps/…/resources.spec.ts• L211-380
References: apps/…/resources.ts• L120-127 apps/…/resources.ts• L157-180 apps/…/resources.ts• L234-305 apps/…/resources.ts• L413-494 apps/…/request.ts• L204-218 apps/…/safe_fetch.ts• L212-258 apps/…/resources.spec.ts• L81-134 apps/…/resources.spec.ts• L169-198 apps/…/resources.spec.ts• L309-380
Database lifecycle
Server SQL provider
The core SQL service depends on a small DatabaseProvider contract rather than on one database library. The server supplies a better-sqlite3 provider that opens the document file or an in-memory copy, prepares statements, runs transactions, and makes a safe database copy for backup. This boundary lets the same core storage rules run on other platforms with another SQLite provider.
The SQL service adds common query shapes, prepared-statement reuse, parameter batching, read-only protection, transaction callbacks, and database copy support. A transaction commit notifies connected clients of entity changes. Browser clients receive these messages through the HTTP-attached WebSocket provider, which checks the session when a connection opens and can ask clients to reload before closing their connections. A rollback reloads the in-memory note view and repairs the tracked change position. apps/…/main.ts• L48-73 and apps/…/ws_messaging_provider.ts• L46-161
References: packages/…/types.ts• L21-53 packages/…/sql.ts• L23-33 packages/…/sql.ts• L286-295 packages/…/sql.ts• L372-407 apps/…/sql_provider.ts• L9-89 apps/…/main.ts• L36-73 apps/…/ws_messaging_provider.ts• L46-161 apps/…/ws_messaging_provider.spec.ts• L99-195
Database initialization
Initialization decides whether the document can be opened before normal services use it. A database is ready only when its schema exists and its initialized option is true. The server enters setup mode before opening the database when a setup marker asks for it, so setup can create or replace a document without normal note activity using the old state.
New-document setup applies the schema, creates the root note and its first branch, adds base options, and then builds system notes and optional demo content. Sync setup creates the schema and only the options needed to receive a database from a sync source. Both paths run as database transactions and leave the instance uninitialized until the selected setup path is complete. packages/…/sql_init.ts• L32-81 and packages/…/sql_init.ts• L137-253
When initialization completes, the dbReady signal releases the Becca loader, scheduled backups, and cleanup services. The server starts the core with its file provider and schema, then starts the HTTP server. apps/…/main.ts• L27-105
The process error boundary treats startup and running-server failures differently. Before the application is ready, an uncaught exception remains fatal because the server cannot safely claim to serve the document. After readiness, escaped errors are logged and sent to connected clients instead of stopping the server, while repeated messages are throttled. apps/…/process_errors.ts• L38-60, apps/…/process_errors.ts• L80-134, and apps/…/www.ts• L70-94
References: packages/…/sql_init.ts• L32-81 packages/…/sql_init.ts• L117-127 packages/…/sql_init.ts• L137-253 packages/…/sql_init.ts• L273-325 apps/…/main.ts• L27-105 apps/…/process_errors.ts• L38-60 apps/…/process_errors.ts• L80-134 apps/…/www.ts• L70-94
Database replacement and restore
Restore replaces the active document only during setup. The service validates the candidate database, detaches the current connection, exchanges the files, attaches the new database, and lets migration open it. It keeps the old document aside until the new one opens, so an interruption can be recovered at the next start.
Large browser backups reach restore through a resumable chunk upload. Each chunk must start at the number of bytes already received, so gaps and duplicate writes are rejected. The upload checks its total size and available space before it starts, keeps partial data after a broken connection, and removes abandoned data after expiry or a restart. apps/…/chunked_upload.ts• L11-26, apps/…/chunked_upload.ts• L177-238, and apps/…/chunked_upload.ts• L241-287
After all chunks arrive, the restore service moves the assembled file into a pending-backup location and holds setup until the restore or discard completes. The same restore path also accepts a backup that already exists on the device. This gives uploaded and local backups the same passphrase, validation, retry, and cleanup behavior. apps/…/restore_session.ts• L21-32, apps/…/restore_session.ts• L90-119, and apps/…/restore_session.ts• L191-245
The setup routes remain unavailable to a live database. When an existing knowledge base is attached behind the setup wizard, a setup authorization token is required before a restore can replace it. This protects the database during the period when ordinary session authentication cannot provide the setup identity. apps/…/routes.ts• L60-75 and apps/…/auth.ts• L112-131
The server checks that an input is a sound Trilium database before the swap. The checks cover SQLite format, integrity, required tables, completed initialization, and a supported database version. A path supplied by a client is also limited to approved backup directories. apps/…/database_restore.ts• L29-47 and packages/…/database_validation.ts• L96-146
References: apps/…/database_restore.ts• L29-47 apps/…/database_restore.ts• L244-280 packages/…/database_validation.ts• L20-44 packages/…/database_validation.ts• L96-146 apps/…/sql_provider.ts• L48-65 apps/…/chunked_upload.ts• L11-26 apps/…/chunked_upload.ts• L177-238 apps/…/chunked_upload.ts• L241-287 apps/…/restore_session.ts• L90-119 apps/…/restore_session.ts• L191-245 apps/…/routes.ts• L60-75 apps/…/auth.ts• L112-131
Note services
Note creation and tree state
The note service is the main coordinator for changes to notes and their placement in the tree. It validates the parent, chooses a note type and content format, creates the note and branch together, applies attributes and templates, and emits change events after the new state is complete. The tree service protects the graph from cycles and records order changes when notes move or are sorted.
Notes may be cloned through several branches while keeping one note record. Deletion first marks notes and related rows as deleted. This preserves enough state for undo and sync before later cleanup removes rows and blobs that no longer have an owner. packages/…/notes.ts• L196-349 and packages/…/tree.ts• L16-78
References: packages/…/notes.ts• L196-220 packages/…/notes.ts• L223-349 packages/…/tree.ts• L16-78 packages/…/bnote.ts• L166-209
Note content processing
Saving note content also maintains the relationships encoded inside that content. The service turns inline data into attachments, normalizes local attachment links, finds links to other notes, and removes relations that no longer exist in the content. It applies this work to text, Markdown, maps, spreadsheets, canvases, and other note formats that carry links or embedded media.
The attachment scan understands the different reference forms used by these formats. HTML and Markdown use attachment links, spreadsheets and canvases store image references in structured content, mind maps store picture URLs, and link previews store picture metadata. The scan keeps referenced attachments alive, replaces pasted foreign attachment IDs with local copies when needed, and schedules unused user attachments for erasure while preserving generated preview files.
LLM chat notes use the same persisted-link model. Links in assistant text and tool inputs become note relations, while user and system text does not create relations. Invalid or incomplete content is ignored without breaking the save path. packages/…/notes.ts• L918-1050 and packages/…/notes.ts• L1292-1329
Some work runs after the main content write. Link previews can fetch and store pictures after the note is saved. The server validates note-provided URLs and their resolved addresses before connecting, pins direct connections to the checked addresses, caps the response size, and stores a usable original when image compression is disabled or fails. Configured API calls use a separate policy that can reach operator-selected private services, has no built-in deadline for long model responses, and refuses redirects so credentials do not move to another target. Automatic compression is bounded so large imports do not overload the server. Imports run the link scan as well, so imported notes have usable links before a person opens them. apps/…/request.ts• L204-305 and apps/…/safe_fetch.ts• L36-55, apps/…/safe_fetch.ts• L212-273, and apps/…/image_provider.ts• L55-135
References: packages/…/notes.ts• L918-968 packages/…/notes.ts• L972-1050 packages/…/notes.ts• L1292-1329 apps/…/notes.ts• L107-147 apps/…/notes.spec.ts• L99-685 apps/…/notes.spec.ts• L689-980 apps/…/notes.spec.ts• L983-1118 apps/…/request.ts• L204-305 apps/…/safe_fetch.ts• L36-55 apps/…/safe_fetch.ts• L212-273 apps/…/image_provider.ts• L55-135
Attachment services
Attachments provide larger or binary data related to a note. Each attachment has a role, media type, title, order, and blob. The attachment API can list and read attachments, save or upload content, rename or delete an attachment, and convert an attachment into a new note.
Images uploaded through the API are stored as image attachments and return a local image URL. Other files return a note attachment view. When an attachment becomes a note, the service creates the new note, removes the old attachment, and rewrites local links in the parent content so they point to the new note. packages/…/attachments.ts• L13-124 and packages/…/battachment.ts• L150-223
Attachment lifetime follows note content. When content no longer refers to an embedded attachment, the note service schedules that attachment for erasure. The cleanup service later removes expired attachment rows and then removes blobs that no note, revision, or attachment still uses. packages/…/erase.ts• L98-120 and packages/…/erase.ts• L174-213
References: packages/…/attachments.ts• L13-124 packages/…/battachment.ts• L33-67 packages/…/battachment.ts• L150-223 packages/…/erase.ts• L98-120 packages/…/erase.ts• L174-213
Revisions and persisted special notes
Revisions preserve snapshots of editable note content at configured intervals. File and image notes are not versioned through the same snapshot path. Protected notes also protect their revisions and revision attachments so the history does not weaken the note's protection.
Some product state is itself stored as notes. Special-note services create and find durable inbox, search, SQL console, launcher, and LLM chat notes. This lets user-facing state use the same tree, content, clone, and sync rules as ordinary notes. LLM chat persistence is also used by the intelligence features described in Server intelligence and automation. packages/…/special_notes.ts• L40-145 and packages/…/special_notes.ts• L280-387
References: packages/…/notes.ts• L1053-1071 packages/…/revisions.ts• L5-42 packages/…/special_notes.ts• L40-145 packages/…/special_notes.ts• L280-387
Note export
Note export turns note content and its related files into portable ZIP packages. The server selects an HTML, Markdown, or share export provider and supplies the HTML provider with the content styles needed for a readable exported note. apps/…/factory.ts• L7-39
The export boundary keeps format choice separate from the stored note model. This allows exported notes to preserve their content for use outside the server without changing the database records that support normal note access.
References: apps/…/factory.ts• L1-39
Backup and maintenance
Backup service
The backup service is a platform-neutral contract for immediate backups, scheduled backups, backup listing, backup reads, and streamed downloads. The server implementation writes plain database files or compressed and encrypted .tnbackup containers. Scheduled checks cover daily, weekly, and monthly policies and run while the database is protected from concurrent sync activity.
The server stores backups in the configured backup directory and can also use a configured custom directory where the platform allows it. If a custom write fails, it falls back to the default location. Backup download paths are accepted only when they resolve inside a known backup directory. packages/…/backup.ts• L26-159 and apps/…/backup_provider.ts• L60-114
References: packages/…/backup.ts• L26-37 packages/…/backup.ts• L69-159 apps/…/backup_provider.ts• L20-45 apps/…/backup_provider.ts• L60-114 apps/…/backup_provider.ts• L145-184
Backup and restore interfaces
The backup API exposes the existing backup list, an immediate backup action, and a download stream. Large server backups are streamed from disk instead of being loaded into memory first. Restore is kept separate from ordinary backup download and runs through setup-only checks before it can replace the document. packages/…/backup.ts• L5-41
The restore interface also supports browser uploads as a sequence of bounded chunks. It reports the received byte count so a client can resume after a broken request, then hands the completed file to the restore service without copying the full database a second time. apps/…/chunked_upload.ts• L241-325 and apps/…/restore_session.ts• L90-119
The server data directory defines the document path, backup location, logs, temporary files, resource files, and related data paths. Each location can be changed with its own environment setting, which makes the data directory part of the deployment contract. Startup creates missing working directories and stops early when existing files or directories are not usable by the server process. apps/…/data_dir.ts• L42-60 and apps/…/data_dir.ts• L62-112
References: packages/…/backup.ts• L5-47 apps/…/backup_provider.ts• L159-185 apps/…/data_dir.ts• L16-40 apps/…/data_dir.ts• L42-60 apps/…/data_dir.ts• L62-112 apps/…/chunked_upload.ts• L241-325 apps/…/restore_session.ts• L90-119
Cleanup and space reporting
Cleanup turns soft deletion into physical deletion after the configured delay. It removes deleted notes and their dependent branches, attributes, revisions, and attachments. It then removes unreferenced blobs. A separate hourly pass handles attachments that content processing marked as unused.
Space reporting explains where storage goes without changing it. It measures note content, attachments, revisions, deleted notes, and unused attachments while counting cloned notes through one canonical tree placement. This gives the content manager both per-note figures and reclaimable totals. packages/…/erase.ts• L122-213 and packages/…/space_usage.ts• L17-35
References: packages/…/erase.ts• L122-213 packages/…/erase.ts• L193-213 packages/…/space_usage.ts• L17-35 packages/…/space_usage.ts• L64-108
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the
DatabaseProvidercontract aligned with every platform provider. Restore, backup, serialization, and detach behavior must match the provider capabilities. - Keep schema changes aligned with initialization, migration, database validation, Becca loading, sync entity changes, and any SQL console schema exposure.
- Keep note content link formats aligned with attachment lifetime checks. A new embedded-media or structured-content format must preserve attachment references and generated preview exemptions or it can trigger unwanted erasure.
- Keep chat content link rules aligned with persisted relation cleanup. Changes to assistant blocks or tool-call shapes can create stale or missing note relations.
- Keep soft-delete and physical-erasure changes aligned with undelete, sync tombstones, dependent rows, and blob reachability.
- Keep backup path and container changes aligned with backup listing, safe path resolution, streamed download, restore validation, and deployment data-directory settings.
- Keep resource definitions and download-state changes aligned with the configured resource directory, client progress messages, content hashes, resume behavior, and license notices.
- Keep transaction commit and rollback hooks aligned with client notifications, Becca reloads, and entity-change tracking.
- Keep WebSocket session checks, client reload messages, and connection cleanup aligned with the delivery of persisted-state changes.
- Keep image and resource fetch policies aligned with URL validation, DNS pinning, redirect rules, response-size limits, proxy behavior, and the separate trust level for configured API endpoints.
- Keep setup authorization aligned with every route that can upload, stage, replace, or discard a database while the setup wizard is active.
- Keep chunked-upload offset checks, ownership transfer, expiry cleanup, and restore setup holds aligned so partial backup files cannot block setup or be deleted after restore takes ownership.
- Keep the application-ready boundary aligned with database startup and service registration. Startup storage failures must remain fatal, while post-ready background failures must be logged and surfaced without taking down the server.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
The schema exists but initialized is not true | The server treats the document as setup state and does not open normal note services | Complete one initialization path and emit the database-ready signal only after it finishes |
| A restore input is corrupt, not a Trilium database, or outside the supported version range | The document is rejected before it can replace the active database | Run database integrity, required-table, initialization, and version checks before the file swap |
| The database connection is detached during a transaction | The restore can leave an incomplete transaction and an unusable connection | Refuse detach while a transaction is active and run replacement only during setup |
| A restore route reaches an existing knowledge base without setup authorization | An unauthenticated setup request could replace or erase the database | Require the setup token whenever setup is protecting an attached database |
| A chunk starts at an offset other than the received byte count | The assembled backup has a gap or duplicate bytes | Accept only the next sequential offset and serialize writes for each upload |
| A browser upload exceeds its declared size or available disk space | The server can waste disk space or fail after a long transfer | Check space before upload and cap bytes while they stream to disk |
| The server restarts or an upload expires before restore takes ownership | The client sees a final gone or expired upload and its partial file is removed | Stamp sessions by process, report restart as gone, and sweep unclaimed files |
| An uncaught storage error occurs before the application is ready | The server can appear usable while its database or migration state is unsafe | Log the error and keep startup-fatal errors fatal until markAppReady() |
| A background error repeats in a loop | Logs and client notices can flood the system | Throttle repeated messages and clear bounded tracking when too many distinct messages appear |
| A client sends a backup path outside an approved backup directory | An arbitrary server file could be read as a backup | Resolve the path and require it to be inside a known backup directory |
| Content processing misses an attachment reference in HTML, Markdown, or structured note data | A still-used attachment can be scheduled for erasure | Update link scanners and attachment-reference checks together when a content format changes |
| A resource file has the wrong size or SHA-256 | The feature cannot use the file and the resource remains uninstalled | Verify each file before renaming it into place and record only verified files |
| A resource download stalls or the connection ends | The download fails while valid partial data may remain for the next attempt | Abort stalled requests and resume only from a checked partial file and matching range |
| The resource definition changes after installation | The old files can be mistaken for the current resource | Include file paths and hashes in the resource directory identity and install the new definition separately |
| A note or downloaded-resource URL resolves to a private or changed address | The server can reach a network target that content should not control | Validate the URL and every resolved address before the request, then pin the connection to the checked addresses |
| A configured API request follows a redirect | An authorization header or API key can reach a host outside the configured endpoint | Refuse redirects for credential-bearing API requests |
| A configured API request blocks on the default short timeout | A long-running model completion can fail before it returns | Let the caller's abort signal control requests that opt out of the built-in deadline |
| Automatic image compression overloads the server or fails over to a blocking decode | Imports slow down or the application becomes unresponsive | Bound incoming compression and keep failed worker images on the original-image path |
| Foreign attachment IDs remain in pasted content | The note points at another note's attachment and later saves can keep repairing the same reference | Copy or reuse an equivalent local attachment and rewrite every foreign reference |
| A note is physically erased before an undo request | The note and its dependent state cannot be restored | Use soft deletion first and delay physical erasure by the configured retention period |
| A protected note is read or changed without an active protected session | Content is withheld or the write fails instead of exposing protected data | Gate decryption and protected writes on protected-session availability |
| A backup is read into memory before download | A large backup can exhaust the server or client process | Use the server's streamed backup response when the provider supports it |
| A WebSocket message or connection error escapes its connection handler | One bad client can disrupt state updates or crash the server process | Catch message and socket errors, remove the affected client, and keep other connections active |
Key files
| File | Why to read it |
|---|---|
| apps/…/main.ts | Shows how the server wires the SQLite provider, core initialization, backup provider, schema, and startup sequence. |
| apps/…/sql_provider.ts | Shows the server's implementation of the shared database-provider boundary. |
| packages/…/types.ts | Defines the capabilities required from a database provider. |
| packages/…/sql.ts | Shows the shared query, transaction, read-only, and database-copy service. |
| packages/…/sql_init.ts | Explains database readiness, new-document setup, sync setup, and partial-schema recovery. |
| packages/…/schema.sql | Defines the durable relationships among notes, branches, attributes, blobs, attachments, revisions, options, and change records. |
| packages/…/becca_loader.ts | Shows how durable rows become the in-memory note view and how later entity changes update it. |
| packages/…/notes.ts | Coordinates note creation, content processing, attachments, revisions, deletion, and restoration. |
| apps/…/notes.spec.ts | Defines the content-link and attachment-reference behaviors that protect stored media and note relations during saves. |
| packages/…/abstract_becca_entity.ts | Shows the shared persistence and blob-content rules used by note-related entities. |
| packages/…/battachment.ts | Explains attachment ownership, content access, and conversion into notes. |
| apps/…/request.ts | Provides server request paths for sync, note resources, images, and configured API endpoints. |
| apps/…/safe_fetch.ts | Defines URL, DNS, redirect, timeout, and private-network policies for server-side outbound requests. |
| apps/…/request.spec.ts | Verifies request transport, cookie handling, image fetch safety, proxy behavior, and response error handling. |
| apps/…/safe_fetch.spec.ts | Verifies address policy, DNS pinning, redirect checks, request cancellation, and response cleanup. |
| apps/…/image_provider.ts | Shows how incoming images are compressed, resized, and kept safe under bounded load. |
| apps/…/factory.ts | Shows how the server selects providers for portable note exports. |
| packages/…/backup.ts | Defines the platform-neutral backup contract and periodic policy. |
| apps/…/backup_provider.ts | Shows server backup formats, directories, synchronization exclusion, and safe streaming. |
| apps/…/data_dir.ts | Defines deployment paths and the startup checks that protect the server from unusable data-directory entries. |
| apps/…/resources.ts | Coordinates verified downloads, resource status, progress, cleanup, resume, and license notices for feature files. |
| apps/…/resources.spec.ts | Shows the guarantees for resource verification, resume, cancellation, replacement, and foreign-entry cleanup. |
| apps/…/ws_messaging_provider.ts | Shows how authenticated browser clients receive persisted-state messages and how their connections are closed safely. |
| apps/…/database_restore.ts | Explains setup-only database replacement and interrupted-restore recovery. |
| apps/…/restore_session.ts | Connects uploaded and local backups to the pending-restore flow and protects setup during replacement. |
| apps/…/chunked_upload.ts | Defines the resumable upload contract used to receive large restore files. |
| apps/…/auth.ts | Shows how setup authorization protects database replacement while normal authentication is unavailable. |
| apps/…/process_errors.ts | Defines the startup readiness boundary and the handling of escaped server errors. |
| packages/…/erase.ts | Shows soft-delete cleanup and blob reclamation. |
| packages/…/space_usage.ts | Shows how storage use is measured and grouped for the content manager. |
| packages/…/special_notes.ts | Shows which user-facing state is persisted as notes, including SQL console and LLM chat state. |