Deck

Local-First, Multi-Layered Search Architecture

Engineering5 min read

How Deck combines SQLite FTS5 trigram indexing, SIMD-accelerated fuzzy matching, bilingual NLEmbedding, sqlite-vec, and Unicode PUA rule tokens—with graceful degradation under AES-GCM encryption.

Newsroom

Search decides whether a clipboard manager stays useful after the first week. Once your history reaches tens of thousands of entries—code snippets, URLs, screenshots with OCR text, and notes—scrolling is no longer viable.

Cloud apps can ship every record to Elasticsearch or Algolia. Deck has no server, no search cluster, and no telemetry pipeline: everything stays on your Mac. The entire search stack is built directly on SQLite, Apple's Natural Language and Accelerate frameworks, and sqlite-vec.

Why One Search Algorithm Is Never Enough

Local clipboard search fails quickly if you rely on a single strategy:

  • Full-text indexes are fast, not forgiving. SQLite FTS5 cannot recall "screnshot" when the user meant "screenshot", and its default unicode61 tokenizer breaks on Chinese, Japanese, and Korean words without spaces.
  • Fuzzy matching tolerates typos, not scale. Scanning tens of thousands of raw clipboard strings character-by-character on every keystroke stalls typing unless bounded and pre-filtered.
  • Semantic embeddings understand intent, not exact tokens. Searching "connection timeout" should surface "network error", yet embeddings alone miss exact variable names, hex codes, or URLs.

Deck answers this by stacking five complementary layers—database full-text indexing, SIMD/byte-level in-memory matching, bilingual NLEmbedding vectors, persistent sqlite-vec kNN retrieval, and structured slash-rule tokens—and fusing their results with Reciprocal Rank Fusion.

Layer 1: SQLite FTS5 with Trigram CJK Support

Deck maintains a content-backed FTS5 virtual table (ClipboardHistory_fts) across search_text, app_name, and custom_title in DeckSQLManager+Schema.swift. At startup, ensureFTSTrigramIfAvailable() probes whether the active SQLite build supports tokenize='trigram' and upgrades legacy unicode61 tables automatically in the background.

Query construction in buildFTSQuery adapts to the active tokenizer:

Propertytrigramunicode61
Minimum term length3 characters1 character
Match syntaxExact 3-gram phrase ("term")Prefix match ("term"*)
CJK recallNative substring recallSplits on whitespace only
Fallback when query is < 3 CJK charsKeyset-paginated searchWithLikeKeyset-paginated searchWithLike

FTS5 triggers (ClipboardHistory_ai, ad, au) are guarded with WHEN new.is_encrypted = 0 and AFTER UPDATE OF search_text, app_name, custom_title, is_encrypted, so tag edits never trigger full-text index rewrites and encrypted rows never leak plaintext tokens into the FTS table.

Layer 2: In-Memory Matching and Byte-Level FuseSearch

When a user types into the panel, SearchService executes exact, fuzzy, regex, or mixed (exact → regex → fuzzy) matching over the candidate set:

  • ASCII fast path: For exact matching, asciiContains uses a KMP failure table over contiguous UTF-8 bytes when both query and text are printable ASCII, avoiding Foundation NSString collation overhead.
  • Byte-level FuseSearch: In FuseSearch.swift, classifySimpleText scans UTF-8 in SIMD16<UInt8> chunks. When all scalars are simple (no combining marks or joiners), fuzzy matching bypasses Swift Character grapheme iteration and runs memmem / memchr directly on UTF-8 bytes.
  • Prepared text cache: Lowercased strings are cached in an NSCache capped at 800 entries and 8 MB, and automatically purged on willResignActive / sessionDidResignActive when Security Mode is enabled.

Fuzzy matches are ranked in fuzzyResult with a 0.6 threshold:

score = 1.0 - (consecutiveBonus * 0.5 + startBonus * 0.3 + coverageRatio * 0.2)

Layer 3: Bilingual On-Device NLEmbedding

In Hybrid (semantic) mode, SemanticSearchService generates sentence and word embeddings completely offline using Apple's Natural Language framework—no external model downloads and no outbound API requests.

One early pitfall in bilingual semantic search is vector-space mismatch. Mixing vectors from .sentenceEmbedding(for: .simplifiedChinese) and .wordEmbedding(for: .simplifiedChinese) produces meaningless cosine scores even if dimensions match. Deck pins each text to an explicit EmbeddingStrategy (nl-embedding-v3-cjk-word-space):

  • Chinese text: Uses NLEmbedding.wordEmbedding(for: .simplifiedChinese) (chineseWordMean), averaging tokenized word vectors (up to 32 tokens) in one consistent space.
  • Non-Chinese text: Uses NLEmbedding.sentenceEmbedding(for: .english) (englishSentence).

For in-memory re-ranking, cosine similarity runs in 256-row blocks (matrixBlockSize = 256) using Accelerate's cblas_sgemv / vDSP, with dynamic minimum score thresholds calibrated by query length (0.18 for 2-character queries, 0.12 up to 4 characters, 0.08 beyond).

To keep resident RAM low when the clipboard panel is closed:

  • Item embeddings are deferred while the panel is inactive and computed in batches when needed.
  • Computed EmbeddingBox entries (vector + cached L2 norm) sit in a 400-item NSCache.
  • Loaded NLEmbedding models are automatically released 30 seconds (embeddingReleaseDelay = 30.0) after panel activity stops.

Layer 4: Persistent Vector Index with sqlite-vec

When history grows past a few hundred entries, computing embeddings on the fly is too slow. Deck compiles sqlite-vec statically (SQLITE_CORE) and registers it via sqlite3_vec_init on both the writer and a dedicated read-only vector connection in DeckSQLManager+VectorIndex.swift.

Vectors are L2-normalized, stored as compact Float32 little-endian binary blobs in ClipboardHistory_embedding, and indexed inside vec0 virtual tables keyed by vector dimension (vec0(embedding float[dim])).

At query time, searchVecCandidates pushes item_type and tag_id filters into the vec0 query before kNN selection:

SELECT rowid, distance FROM ClipboardHistory_vec_512
WHERE embedding MATCH ?
  AND rowid IN (SELECT id FROM ClipboardHistory WHERE item_type IN (?) AND tag_id = ?)
ORDER BY distance
LIMIT ?

Filtering inside vec0 avoids a classic kNN bug where post-filtering top-K global neighbors drops valid results that sat just below rank K.

Finally, DeckDataStore+HybridSearch.swift runs sqlite-vec neighbor retrieval and SQL LIKE literal matching concurrently, merges both candidate sets using Reciprocal Rank Fusion (1 / (61 + offset)), projects lightweight search summaries, and applies lexical + title-priority reranking before hydrating full cards.

Layer 5: Slash-Rule Filters via Unicode PUA

Power users frequently combine keywords with metadata constraints—such as finding an image from Figma copied last week (app:Figma type:image date:7d). Typing / in Deck's search bar inserts a colored capsule token (NSTextAttachment) backed by Unicode Private Use Area characters in SearchRuleFilters.swift:

enum SearchRuleToken {
    static let app: Character = "\u{E000}"
    static let date: Character = "\u{E001}"
    static let type: Character = "\u{E002}"
    static let lang: Character = "\u{E003}"
    static let size: Character = "\u{E004}"
    static let marker: Character = "\u{2063}" // Invisible prefix marker
}

Using Private Use Area code points plus the invisible separator U+2063 prevents rule tokens from colliding with literal text the user types (such as a file path or regex starting with /). Every rule dimension—date, app, type, lang, and size—also supports negation (/-app:Safari).

Graceful Degradation Under Encryption

When Biometric Protection (Security Mode) is enabled, Deck encrypts search_text, app_name, custom_title, data, and embedding columns with AES-256-GCM before writing them to SQLite. Ciphertext cannot be indexed by FTS5 or vec0.

Rather than leaking plaintext tokens into secondary indexes or disabling search altogether, Deck shifts cleanly to an authenticated in-memory path:

CapabilityStandard ModeSecurity Mode (Encrypted)
FTS5 full-text indexActive (trigram / unicode61)Disabled and cleared
sqlite-vec vector indexActive (vec0)Disabled (vecSearchAllowed = false)
Fallback scanKeyset-paginated searchWithLikeBatch decrypt + in-memory match (searchWithLike)
Scan capUnbounded keyset batchesmin(max(5000, limit * 200), 20000) recent rows
Decrypted text cacheNot requiredBounded NSCache (cleared when app resigns active)

Security and indexing speed are always in tension. Making that trade-off explicit means encrypted histories never write unencrypted search terms to disk while keeping recent-item search responsive.

You can inspect the full search and storage implementation on GitHub or download Deck for macOS.

More from the Newsroom

Download Deck

Free.macOS 14 or later,Apple silicon and Intel.

DownloadD