Commit 323a647574
323a647574ab2c88f6d95bba6b71eca0b9611bba
parent: f783dd307a
Unsigned
cmc <hello@cleberg.net> · 2026-10-21 07:40 UTC
Library search: folded index as UTF-8 bytes searched with memmem, built off main at launch (!78)
`Library.search` runs from `LibraryScreen.body` on every keystroke. It ran Swift `String.contains` over 480 KB of folded text in 370 pages, 9–12 ms for any query of four or more letters that does not hit a title. The index was built on the first search.
## Changes
- `Library.searchIndex` stores the folded head (title, subtitle) and body (essay, fact values) as `[UInt8]`; `search` matches them with `memmem`. Folding (case, diacritics), the `id` match and the strong/weak order are unchanged.
- `Library.prepareSearch()` builds the index. `AppDelegate` calls it from a detached utility task at launch, next to the App Shortcuts update, which already decodes `Library.pages` off main.
- Test `searchMatchesFoldedStringContains` compares `search` with the previous `String.contains` matching: single characters, "Señor"/"SENOR", "Cygnus"/"Cýgnus", "Méchain", "Ångström", multi-word, padded, no-match, "M31", "m42", "M 13", "Messier 101", "NGC 224", "HR 2491", Greek ("α Centauri", "ω Centauri", "Σ", "σ"), page ids and every tenth page title.
- A one-off run outside the test compared both over 13,729 queries (every word, character and character pair in the pages, every title, upper-cased title and id): no differences. After folding the pages contain no combining marks and no CR; the non-ASCII characters left are `°±²³·×αβγδεζηκνσ–′⁰⁴−`.
## Measurements
**Package benchmark** (`perf/` release harness, M2 Pro, `-c release`, medians of 142–400 runs, two runs each side agreed within 3%). Load (`uptime`, 12 cores): main 2.75 → 2.76, branch 3.51 → 3.47.
| `Library.search` | main | branch |
|---|---:|---:|
| "m" | 0.45 ms | 0.09 ms |
| "or" | 1.69 ms | 0.19 ms |
| "orion" | 9.78 ms | 0.44 ms |
| "andromeda galaxy" | 10.51 ms | 0.50 ms |
| "zzzz" | 9.39 ms | 0.29 ms |
Fresh process, median of 5: first search ("orion", includes decoding pages and building the index) 30.8 → 20.9 ms; `Library.pages` alone 14.3 ms on both; `prepareSearch()` 20.4 ms. Footprint after the first search 7.1 → 7.0 MB.
**iPhone 18 Pro simulator** (iOS 27, Release build). A temporary probe (not committed) timed each `Library.search` call in `LibraryScreen` and the `prepareSearch` task. A UI test opens Library, types "andromeda galaxy", clears, types "orion", clears, types "zzzz". 3 runs each side.
| `Library.search` per body evaluation | main | branch |
|---|---:|---:|
| First search of the run ("a" or "an") | 5.2–6.1 ms | 0.17–0.21 ms |
| "andromeda galaxy" | 11.4–12.7 ms | 0.55–0.57 ms |
| "orion" | 10.4–10.6 ms | 0.50–0.52 ms |
| "zzzz" | 9.4–9.6 ms | 0.34 ms |
| Longest of any evaluation | 12.7 ms | 0.60 ms |
On main the first search cost 5–6 ms rather than ~31 ms: the pages were already decoded at launch, and what remains is building the index (about 6 ms in the benchmark, 20.4 − 14.3 ms) plus the search. `prepareSearch` started 3 ms after `didFinishLaunching` and took 30–35 ms on a background thread; it finished about 400 ms before the first frame.
Load: main 2.76 → 2.91, 2.91 → 3.22, 3.22 → 3.64; branch 3.67 → 3.24, 3.24 → 3.36, 3.36 → 4.09.
## Tests
- `swift test` (MoonriseKit): pass (195 tests).
- `npm test` (server): 55 pass.
- `xcodebuild test` (iPhone 18 Pro): pass. The accessibility audit found 64 issues: Sky 4, Settings 2, System 7, Sun 3, News & launches 21, Library 14, Library page: Saturn 13. These are the counts reported for main in !77.
## Not verified
- On a device.
- That the App Shortcuts update had decoded the pages before the first search on main is inferred from the timings, not traced.
- The accessibility audit was not run on main in this session.
Layout: unified · split
App/Sources/MoonriseApp.swift
+2
| @@ -1,4 +1,5 @@ |
| 1 | import AppIntents |
1 | import AppIntents |
| |
2 | import Library |
| 2 | import SkyRenderer |
3 | import SkyRenderer |
| 3 | import SwiftUI |
4 | import SwiftUI |
| 4 | import UIKit |
5 | import UIKit |
| @@ -46,6 +47,7 @@ final class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCent |
| 46 | UNUserNotificationCenter.current().delegate = self |
47 | UNUserNotificationCenter.current().delegate = self |
| 47 | application.registerForRemoteNotifications() |
48 | application.registerForRemoteNotifications() |
| 48 | MoonriseShortcuts.updateAppShortcutParameters() |
49 | MoonriseShortcuts.updateAppShortcutParameters() |
| |
50 | Task.detached(priority: .utility) { Library.prepareSearch() } |
| 49 | Task.detached(priority: .background) { await SpotlightIndexer.indexIfNeeded() } |
51 | Task.detached(priority: .background) { await SpotlightIndexer.indexIfNeeded() } |
| 50 | return true |
52 | return true |
| 51 | } |
53 | } |
Packages/MoonriseKit/Sources/Library/Library.swift
+14 −4
| @@ -139,16 +139,26 @@ public enum Library { |
| 139 | public static func search(_ query: String) -> [LibraryPage] { |
139 | public static func search(_ query: String) -> [LibraryPage] { |
| 140 | let q = fold(query.trimmingCharacters(in: .whitespaces)) |
140 | let q = fold(query.trimmingCharacters(in: .whitespaces)) |
| 141 | guard !q.isEmpty else { return [] } |
141 | guard !q.isEmpty else { return [] } |
| |
142 | let needle = Array(q.utf8) |
| 142 | var strong: [LibraryPage] = [], weak: [LibraryPage] = [] |
143 | var strong: [LibraryPage] = [], weak: [LibraryPage] = [] |
| 143 | for entry in searchIndex { |
144 | for entry in searchIndex { |
| 144 | if entry.head.contains(q) || entry.page.id == q { strong.append(entry.page) } else if entry.body.contains(q) { weak.append(entry.page) } |
145 | if contains(entry.head, needle) || entry.page.id == q { strong.append(entry.page) } else if contains(entry.body, needle) { weak.append(entry.page) } |
| 145 | } |
146 | } |
| 146 | return strong + weak |
147 | return strong + weak |
| 147 | } |
148 | } |
| 148 | |
149 | |
| 149 | /// Lowercased, diacritic-free text per page, built once: title and subtitle, then essay and facts. |
150 | /// Builds the search index. Call off the main thread so the first search does not pay for it. |
| 150 | private static let searchIndex: [(page: LibraryPage, head: String, body: String)] = pages.map { p in |
151 | public static func prepareSearch() { |
| 151 | (p, fold(p.title + "\n" + p.subtitle), fold(p.essay + "\n" + p.facts.map(\.value).joined(separator: "\n"))) |
152 | _ = searchIndex |
| |
153 | } |
| |
154 | |
| |
155 | /// Lowercased, diacritic-free UTF-8 per page, built once: title and subtitle, then essay and facts. |
| |
156 | private static let searchIndex: [(page: LibraryPage, head: [UInt8], body: [UInt8])] = pages.map { p in |
| |
157 | (p, Array(fold(p.title + "\n" + p.subtitle).utf8), Array(fold(p.essay + "\n" + p.facts.map(\.value).joined(separator: "\n")).utf8)) |
| |
158 | } |
| |
159 | |
| |
160 | private static func contains(_ haystack: [UInt8], _ needle: [UInt8]) -> Bool { |
| |
161 | haystack.withUnsafeBytes { h in needle.withUnsafeBytes { n in memmem(h.baseAddress, h.count, n.baseAddress, n.count) != nil } } |
| 152 | } |
162 | } |
| 153 | |
163 | |
| 154 | static func fold(_ s: String) -> String { |
164 | static func fold(_ s: String) -> String { |
Packages/MoonriseKit/Tests/LibraryTests/LibraryTests.swift
+25
| @@ -54,6 +54,31 @@ func linksPointAtThingsTheAppKnows(_ p: LibraryPage) { |
| 54 | #expect(Library.search(" ").isEmpty) |
54 | #expect(Library.search(" ").isEmpty) |
| 55 | } |
55 | } |
| 56 | |
56 | |
| |
57 | @Test func searchMatchesFoldedStringContains() { |
| |
58 | let index = Library.pages.map { p in |
| |
59 | (p, Library.fold(p.title + "\n" + p.subtitle), Library.fold(p.essay + "\n" + p.facts.map(\.value).joined(separator: "\n"))) |
| |
60 | } |
| |
61 | func reference(_ query: String) -> [String] { |
| |
62 | let q = Library.fold(query.trimmingCharacters(in: .whitespaces)) |
| |
63 | guard !q.isEmpty else { return [] } |
| |
64 | let strong = index.filter { $0.1.contains(q) || $0.0.id == q } |
| |
65 | let weak = index.filter { !($0.1.contains(q) || $0.0.id == q) && $0.2.contains(q) } |
| |
66 | return (strong + weak).map(\.0.id) |
| |
67 | } |
| |
68 | let queries = [ |
| |
69 | "a", "m", "z", "q", "x", "1", ".", "-", "–", "°", "(", |
| |
70 | "Señor", "señor", "SENOR", "Cygnus", "cygnus", "CYGNUS", "Cýgnus", "Méchain", "Ångström", "Tycho Brahe", "Kuiper", |
| |
71 | "andromeda galaxy", " Orion Nebula ", "great red spot", "black hole", "light-years", "main sequence", "Hubble's", |
| |
72 | "zzzz", "xyzzy", "qqqq q", |
| |
73 | "M1", "M31", "m42", "M 13", "Messier 101", "NGC 224", "HR 2491", |
| |
74 | "α", "α Centauri", "Alpha Centauri", "β", "ω Centauri", "Omega", "ε Eridani", "η Carinae", "Σ", "σ", |
| |
75 | Library.pages[0].id, Library.pages.last!.id, |
| |
76 | ] + stride(from: 0, to: Library.pages.count, by: 10).map { Library.pages[$0].title } |
| |
77 | for q in queries { |
| |
78 | #expect(Library.search(q).map(\.id) == reference(q), "\(q)") |
| |
79 | } |
| |
80 | } |
| |
81 | |
| 57 | @Test func scaleObjectsComeFromPages() { |
82 | @Test func scaleObjectsComeFromPages() { |
| 58 | let objects = Library.scaleObjects |
83 | let objects = Library.scaleObjects |
| 59 | #expect(objects.first?.name == "ISS") |
84 | #expect(objects.first?.name == "ISS") |