# Local-First, Multi-Layered Search Architecture

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

Engineering · 2026-12-03 · 5 min read

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](https://deckclip.app/) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BSchema.swift#L381-L400). At startup, [`ensureFTSTrigramIfAvailable()`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BSchema.swift#L547-L558) probes whether the active SQLite build supports `tokenize='trigram'` and upgrades legacy `unicode61` tables automatically in the background.

Query construction in [`buildFTSQuery`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BListQueries.swift#L341-L357) adapts to the active tokenizer:

| Property | `trigram` | `unicode61` |
|---|---|---|
| Minimum term length | 3 characters | 1 character |
| Match syntax | Exact 3-gram phrase (`"term"`) | Prefix match (`"term"*`) |
| CJK recall | Native substring recall | Splits on whitespace only |
| Fallback when query is < 3 CJK chars | Keyset-paginated `searchWithLike` | Keyset-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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SearchService.swift#L149-L168) executes `exact`, `fuzzy`, `regex`, or `mixed` (`exact → regex → fuzzy`) matching over the candidate set:

- **ASCII fast path:** For exact matching, [`asciiContains`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SearchService.swift#L272-L289) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Core/Search/FuseSearch.swift#L83-L229), [`classifySimpleText`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Core/Search/FuseSearch.swift#L83-L123) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Core/Search/FuseSearch.swift#L324-L348) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SemanticSearchService.swift#L18-L82) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SemanticSearchService.swift#L440-L468) (`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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BVectorIndex.swift#L49-L71).

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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BVectorIndex.swift#L1039-L1175) pushes `item_type` and `tag_id` filters *into* the `vec0` query before kNN selection:

```sql
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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckDataStore%2BHybridSearch.swift#L138-L154) 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`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search/SearchRuleFilters.swift#L14-L23):

```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:

| Capability | Standard Mode | Security Mode (Encrypted) |
|---|---|---|
| FTS5 full-text index | Active (`trigram` / `unicode61`) | Disabled and cleared |
| `sqlite-vec` vector index | Active (`vec0`) | Disabled (`vecSearchAllowed = false`) |
| Fallback scan | Keyset-paginated `searchWithLike` | Batch decrypt + in-memory match ([`searchWithLike`](https://github.com/yuzeguitarist/Deck/blob/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Storage/DeckSQLManager%2BListQueries.swift#L639-L729)) |
| Scan cap | Unbounded keyset batches | `min(max(5000, limit * 200), 20000)` recent rows |
| Decrypted text cache | Not required | Bounded `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](https://github.com/yuzeguitarist/Deck/tree/f6e922c6e4bf2dfce13b07cf5c759a8526fff29b/Deck/Services/Search) or [download Deck for macOS](https://deckclip.app/download).

---

- HTML: https://deckclip.app/newsroom/search-architecture
- 中文: https://deckclip.app/zh-cn/newsroom/search-architecture.md

© 2026 Yuze Pan
