SPB Git

Repository Public License

PERSISTENCE.md 16.5 KB

# Persistence

Storage layer of ORIX Navigator: Packages/NavigatorKit/Sources/Persistence. System SQLite, no third-party library (rationale: ADR 0002).

# Using it

swift
import Persistence

// At launch (off the main actor by construction: every call is async and runs on the database's own queues).
let (database, recovery) = try await NavigatorDatabase.openRecovering(url: supportDirectory.appending(path: "Navigator.sqlite"))
if let recovery { /* tell the user: the damaged database was moved to recovery.quarantineDirectory */ }

let launch = try await database.session.beginSession()      // launch.recoveredFromCrash
let session = try await database.session.restore()          // profiles, spaces, groups, windows, tabsByWindow

// While running: batch UI changes (debounce in the caller), one transaction per batch.
try await database.session.apply([.touchTab(id: tab.id, url: url, title: title, lastActiveAt: .now)])

// On normal termination.
try await database.session.markCleanShutdown()

NavigatorDatabase vends one store per model: profiles, spaces, windows, tabs, tabGroups, session, history, bookmarks, downloads, permissions, archives, snapshots, notes, canvases, agentRuns, workflows, sync, settings, lifecycle. Tests and previews use NavigatorDatabase.inMemory().

Secrets are not in the database: SecretStore (protocol in NavigatorCore), KeychainSecretStore (Persistence), InMemorySecretStore (NavigatorCore, for tests).

# Architecture

Layer Type Role
Connection SQLiteConnection One SQLite handle. Prepared-statement cache (256 statements), typed binding and reading, transaction { } (BEGIN IMMEDIATE, rollback on throw, savepoints when nested), SQLiteError with code, extended code, message and statement text (never bound values).
Isolation ConnectionActor Actor with a private serial dispatch queue as executor: SQLite never runs on the main thread or on the Swift cooperative pool.
Database SQLiteDatabase One writer and three read-only connections (file databases). read, write, transaction.
Schema Migrator, Schema Versioned migrations.
Stores …Store structs Typed async API; all SQL lives here.
Façade NavigatorDatabase Opening, integrity check, recovery, file protection, stores.

Connection settings: journal_mode = WAL, synchronous = NORMAL, foreign_keys = ON, busy_timeout = 5000, secure_delete = ON, temp_store = MEMORY, journal_size_limit = 64 MiB; readers add query_only = ON.

Concurrency: in WAL mode readers never wait for the writer and the writer never waits for readers. Each read runs inside one deferred transaction, so several statements of a read see one snapshot. A read started after a write returned sees that write. Writes are serialised by the writer actor. An in-memory database has a single connection (reads are serialised with writes).

Durability: every store write is one committed transaction. With WAL + synchronous = NORMAL a commit survives an application crash or force quit. A kernel panic or power loss can lose the most recent commits but cannot corrupt the database.

# Conventions

  • Identifiers: TEXT, UUID string (ID.string).
  • Dates: REAL, seconds since 1970 (UTC). Dates inside JSON columns use the same unit. A Date round-trips to within a quarter of a microsecond (the 1970 offset costs one bit of the mantissa); whole seconds are exact.
  • URLs: TEXT, absoluteString. Booleans: INTEGER 0/1. Enums: TEXT raw value.
  • order in the models is the column sort_order (ORDER is a keyword).
  • What is queried is a real column; nested value types are JSON TEXT: spaces.focus, windows.frame, windows.split, archives.missing, canvas_documents.cards/connections/viewport, agent_runs.steps/citations/usage/budget, settings.value.

# Schema (version 2)

Table Content Notes
schema_migrations applied versions bookkeeping; the authoritative version is PRAGMA user_version
app_state internal key/value session.clean_shutdown, sync.local_version
settings user settings JSON value per key
profiles Profile CHECK (kind = 'standard'): a ghost profile cannot be inserted
spaces OrbitSpace FK profile, cascade
windows BrowserWindow FK space, cascade; closed_at = recently closed
tab_groups TabGroup FK space, cascade
tabs Tab FK window and space (cascade), group (set null), parent (set null, deferred); session_state BLOB; closed_at = recently closed
history_urls one row per (profile, URL) title, counters, last_visited_at, host_key, frecency
history_visits NavigationEntry FK history_urls, cascade
history_fts FTS5 over history_urls(title, url) external content, kept in sync by three triggers
bookmarks, bookmark_tags Bookmark tree through parent_id (cascade); tags ordered by position
downloads Download resume_data BLOB
permissions PermissionDecision unique (profile, scheme, host, port, kind); port −1 = default
archives, page_snapshots Archive, PageSnapshot snapshot → archive is set null
notes, canvas_documents, agent_runs Note, CanvasDocument, AgentRun optional space (set null when the space is deleted)
workflows Workflow not tied to a profile
sync_records SyncRecord unique (entity, entity_id); deleted_at = tombstone

Indexes follow the queries: tabs by (window, closed, order) and by space; closed tabs and windows by closing time; visits by (profile, time) and by URL; URLs by (profile, last visit), (profile, host key) and (profile, frecency); bookmarks by (profile, parent, order), by URL and a partial index on favourites; downloads by (profile, start); sync records by version.

# Migration rules

  1. Schema.migrations is an ordered, append-only list. Adding a schema change is one new Migration(version: n, name: …, sql: …) entry (or a closure for data backfills). Versions are 1, 2, 3… without gaps (checked by a precondition).
  2. A shipped migration is never edited. Helpers a migration calls (HistorySQL.recomputeFrecency, Frecency) are part of its frozen behaviour: change them only together with a new migration that recomputes.
  3. Each migration runs in its own BEGIN IMMEDIATE … COMMIT together with its schema_migrations row and PRAGMA user_version. A failure rolls the whole step back and stops; earlier steps stay applied.
  4. Prefer additive changes (ADD COLUMN with a default, new tables and indexes). A table rebuild sets disablesForeignKeys: true; the migrator then turns foreign keys off around the transaction and refuses to commit if PRAGMA foreign_key_check reports a violation.
  5. A database whose version is higher than Schema.latestVersion is not opened: PersistenceError.databaseTooNew(found:supported:). The file is not modified and is not treated as corrupt.
  6. Every new migration gets a test that builds the previous version with Migrator.migrate(_, upTo:), inserts rows with that version's SQL and opens it with the current code (MigrationTests).

Version history: 1 initial schema. 2 history_urls.host_key and history_urls.frecency with their indexes, backfilled from the stored visits (added when the omnibox ranking was designed).

# Session restoration and crash detection

  • SessionStore.apply([SessionChange]) commits a batch of window/tab changes in one transaction. The caller debounces; what a crash can lose is its debounce window, nothing else. In a batch, a window must precede the tabs that reference it.
  • SessionStore.replaceOpenState(windows:tabs:groups:) writes a full picture and deletes open windows/tabs that are no longer in it (recently closed items are kept).
  • SessionStore.restore() reads profiles, spaces, groups, open windows and open tabs in one snapshot. Tabs come back .dormant. includeSessionState: false skips the WebKit blobs.
  • Clean-shutdown flag (app_state['session.clean_shutdown']): beginSession() returns how the previous run ended and sets the flag to "not clean"; markCleanShutdown() sets it back and truncates the WAL. A crash, a kill or a power cut never reaches markCleanShutdown(), so the next beginSession() reports recoveredFromCrash == true.
  • Recently closed: closing a tab or a window sets closed_at. TabStore.recentlyClosed/reopen, WindowStore.recentlyClosed/reopen, SessionStore.pruneClosed(maxTabs:maxWindows:olderThan:).

# History, search and suggestions

  • recordVisit upserts the URL row (title, counters, frecency) and inserts the visit in one transaction. updateTitle sets the title once the page has loaded.
  • Full-text search (HistoryStore.search): FTS5, tokenizer unicode61 remove_diacritics 2 (case and accents folded), prefix indexes for 1–3 characters. User text never reaches FTS5's query language: FTSQuery splits it into runs of letters and digits and quotes each run, so operators and quotes are plain text and no input can produce a syntax error. All words must match; the last one is a prefix. Limits: ß is not folded to ss; CJK text has no word segmentation (a run of ideographs is one token, matched from its start).
  • Frecency (Frecency): each visit contributes weight × 2^(−age / 30 days) (typed 2, link/form 1, agent/other 0.5, redirect/back-forward 0.25, reload/restore 0). The column stores ln Σ weightᵢ·e^{λ(tᵢ − epoch)}, which orders rows exactly like the decayed sum but does not change as time passes: no periodic recomputation, and adding a visit is one update. Deleting visits recomputes the affected URLs from their remaining visits.
  • Suggestions (HistoryStore.suggestions): candidates are the FTS matches of the typed words; they are ordered by frecency plus a ×4 boost when the typed text is a prefix of the host (ignoring scheme and www.). The cost is proportional to the number of matching URLs, not to the table size.

# Bookmarks and the Netscape HTML format

BookmarkStore.importHTML / exportHTML, parser and writer in NetscapeBookmarks. The reader is a forgiving scanner (unclosed <DT>, missing outer <DL> as in Safari, any attribute case and quoting, multi-kilobyte ICON data URLs, <DD> descriptions, <HR>). It keeps folders, titles, URLs, ADD_DATE / LAST_MODIFIED (seconds, milliseconds or microseconds), Firefox TAGS, and marks links directly inside the PERSONAL_TOOLBAR_FOLDER as favourites. Links that are not http, https, ftp or file (bookmarklets, place: queries, chrome://) are skipped and counted. Nesting is capped at 64 levels. The writer emits UTF-8 with TAGS and a private ORIX_FAVORITE attribute. Safari has no dates and no tags in its export; Safari's favourites folder is not flagged in the file and is imported as an ordinary folder.

# Ghost (private) data

A .ghost profile is never stored, and nothing that belongs to one can be stored:

  1. ProfileStore.save throws PersistenceError.ghostWriteRejected for a ghost profile (and the schema's CHECK (kind = 'standard') refuses it even through raw SQL).
  2. Every other write verifies inside its transaction that its owner is stored — profile for history, bookmarks, downloads, permissions, archives and snapshots; space for windows, groups, notes, canvases and agent runs; window and space for tabs. A ghost profile is not stored, so the chain fails: PersistenceError.ownerNotPersisted.
  3. NavigatorDatabase.ghosts (GhostRegistry) lets the app declare the ids of a ghost session (profile, spaces, windows); writes that reference them then fail with the explicit ghostWriteRejected.

Not covered, by construction: a note, canvas or agent run saved with spaceID == nil, a workflow, a setting or a sync record carries no owner, so the store cannot know it came from a ghost window. Callers must not persist those from a ghost context.

# Corruption and recovery

  • NavigatorDatabase(url:) throws PersistenceError.corrupt(path:details:) when SQLite reports SQLITE_CORRUPT or SQLITE_NOTADB while opening or migrating, or when PRAGMA quick_check fails. The quick check runs when the previous run did not shut down cleanly (IntegrityCheckPolicy.afterUncleanShutdown, the default), always (.always) or never. The file is left as it is.
  • NavigatorDatabase.openRecovering(url:) is the recovery path: on .corrupt it moves the database, -wal and -shm files into <name>.corrupt-<UTC timestamp>/ next to the database, creates a new empty database and returns a RecoveryReport (reason, quarantine directory, moved files). Nothing is deleted. The app must tell the user; the quarantined file can be examined with sqlite3 Navigator.sqlite ".recover".
  • "Too new" is not corruption and is never quarantined.
  • checkIntegrity(full:) runs quick_check or integrity_check on demand.

# Deletion, retention, export

database.lifecycle (DataLifecycle):

  • delete(DeletionRequest(types:profileID:range:)) — any subset of UserDataType (history, bookmarks, downloads, permissions, archives, snapshots, notes, canvases, agentRuns, recentlyClosed, session, workflows, settings, syncRecords), for one profile or all, in a half-open time range or all time; one transaction; returns per-type counts and the archive files to remove from disk. Types without a profile (workflows, settings, syncRecords) are skipped by a profile-scoped request.
  • deleteProfile(_:) — the profile, everything cascading from it, and the notes, canvases and agent runs of its spaces. The caller deletes the profile's WebKit data store and the reported archive files.
  • deleteEverything() — all rows of all profiles, settings and sync records, then FTS rebuild, VACUUM and WAL truncation. Only the schema and the sync version counter remain.
  • HistoryStore.deleteVisits(in:), deleteHost(_:includingSubdomains:), deleteURL, deleteVisit, deleteAll.
  • Retention: applyHistoryRetention(days:now:); applyStoredRetentionPolicy() uses the setting PersistenceSettings.historyRetentionDays (0 = keep forever). The app calls it at launch and daily.
  • Export: exportBundle / exportJSON produce a UserDataBundle (JSON, ISO 8601 dates). It contains no cookies or website storage (WebKit owns them; this module never reads them), no secrets (Keychain), no WebKit session blobs and no download resume data.

Residue after deletion: secure_delete = ON zeroes freed pages in the main file. Deleted content can remain in the WAL until the next checkpoint and in FTS5 segments until they are merged; deleteEverything() and compact() remove both. Selective deletions do not compact automatically.

# Encryption at rest

Stated plainly:

  • The SQLite database is not encrypted by the application. History, bookmarks, tabs, notes and the rest are stored in clear SQLite pages.
  • On iOS and iPadOS the database, WAL and shared-memory files carry FileProtectionType.completeUntilFirstUserAuthentication (open flag plus file attribute): encrypted by the system with a key that is unavailable from boot until the first unlock, available afterwards — including while the device is locked, which background downloads and sync require. It does not protect against someone holding the unlocked device or a backup.
  • On macOS protection is FileVault (full-disk encryption, if the user enabled it) and the app sandbox container's permissions. Any process running as the user outside the sandbox can read the file.
  • Secrets (API keys of AI providers) are only in the Keychain: generic-password items, kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, not synchronised to iCloud, namespaced by service. They are not in the database, not in exports, and SecretStoreError carries a status code only.
  • Ghost data is not written at all.

# Tests

Tests/PersistenceTests (Swift Testing): SQLite layer, migrations (v1 fixture → latest, rollback, too new), corruption and recovery, round trips of every store, session and clean-shutdown flag, history (FTS with Unicode and hostile input, frecency), bookmarks (tree, Netscape import/export), ghost rejection, lifecycle, secret stores. Two tests print measurements ([benchmark] lines): session restoration and omnibox suggestions on 100 000 URLs.

text
cd Packages/NavigatorKit
swift test --disable-keychain --scratch-path build/spm-persistence --filter PersistenceTests
ORIX_KEYCHAIN_TESTS=1 swift test …   # also exercises KeychainSecretStore against the login keychain
Files main
Menu

Theme