Repository Public License
1import Foundation2import NavigatorCore3import Testing4@testable import Persistence56@Suite struct HistoryTests {7 @Test func visitsAggregateIntoPages() async throws {8 let fixture = try await Fixture.make()9 let history = fixture.database.history10 let profile = fixture.profile.id11 let page = url("https://www.example.com/article")12 let first = fixture.visit(page.absoluteString, title: "", at: second(0), transition: .typed)13 let secondVisit = fixture.visit(page.absoluteString, title: "The Article", at: second(60))14 let other = fixture.visit("https://other.example.org/", title: "Other", at: second(30))15 try await history.recordVisit(first)16 try await history.recordVisits([secondVisit, other])17 // Recording the same visit again does not count twice.18 try await history.recordVisit(secondVisit)1920 #expect(try await history.visitCount(profile: profile) == 3)21 #expect(try await history.visits(profile: profile) == [secondVisit, other, first])22 #expect(try await history.visits(profile: profile, in: DateInterval(start: second(0), end: second(31))) == [other, first])23 #expect(try await history.visits(profile: profile, limit: 1, offset: 1) == [other])2425 let stored = try #require(try await history.page(for: page, profile: profile))26 #expect(stored.title == "The Article")27 #expect(stored.visitCount == 2)28 #expect(stored.typedCount == 1)29 #expect(stored.lastVisitedAt == second(60))3031 // A visit without a title does not erase the known one; a late title update reaches the index.32 try await history.recordVisit(fixture.visit(page.absoluteString, title: "", at: second(90)))33 #expect(try await history.page(for: page, profile: profile)?.title == "The Article")34 try await history.updateTitle("Renamed Headline", for: page, profile: profile)35 #expect(try await history.search("headline", profile: profile).map(\.url) == [page])36 #expect(try await history.search("article", profile: profile).map(\.url) == [page]) // still in the URL37 #expect(try await history.visits(profile: profile).first?.title == "Renamed Headline")3839 // Deleting single visits repairs the counters and removes the page with its last visit.40 #expect(try await history.deleteVisit(first.id) == true)41 #expect(try await history.deleteVisit(first.id) == false)42 #expect(try await history.page(for: page, profile: profile)?.typedCount == 0)43 #expect(try await history.page(for: page, profile: profile)?.visitCount == 2)44 #expect(try await history.deleteVisit(other.id) == true)45 #expect(try await history.page(for: other.url, profile: profile) == nil)46 #expect(try await history.search("other", profile: profile).isEmpty)47 }4849 @Test func deleteByRangeHostAndAll() async throws {50 let fixture = try await Fixture.make()51 let history = fixture.database.history52 let profile = fixture.profile.id53 let other = Profile(name: "Other", createdAt: day())54 try await fixture.database.profiles.save(other)5556 try await history.recordVisits([57 fixture.visit("https://news.example.com/a", title: "A", at: day(1)),58 fixture.visit("https://news.example.com/a", title: "A", at: day(5)),59 fixture.visit("https://www.example.com/b", title: "B", at: day(2)),60 fixture.visit("https://example.com.evil.test/c", title: "C", at: day(3)),61 fixture.visit("https://notexample.com/d", title: "D", at: day(4)),62 NavigationEntry(profileID: other.id, url: url("https://news.example.com/a"), title: "A", visitedAt: day(2)),63 ])6465 // Range: [day 2, day 4) removes B and C; A keeps its two visits outside the range.66 #expect(try await history.deleteVisits(in: DateInterval(start: day(2), end: day(4)), profile: profile) == 2)67 #expect(try await history.page(for: url("https://www.example.com/b"), profile: profile) == nil)68 #expect(try await history.search("evil", profile: profile).isEmpty)69 #expect(try await history.page(for: url("https://news.example.com/a"), profile: profile)?.visitCount == 2)70 #expect(try await history.visitCount(profile: other.id) == 1) // other profile untouched7172 // A range that takes only one of the two visits repairs the aggregate.73 #expect(try await history.deleteVisits(in: DateInterval(start: day(5), end: day(6)), profile: profile) == 1)74 let page = try #require(try await history.page(for: url("https://news.example.com/a"), profile: profile))75 #expect(page.visitCount == 1)76 #expect(page.lastVisitedAt == day(1))7778 // Host: example.com covers its subdomains but neither look-alike domain.79 try await history.recordVisit(fixture.visit("https://www.example.com/b", title: "B", at: day(6)))80 #expect(try await history.deleteHost("example.com", profile: profile) == 2)81 #expect(try await history.visits(profile: profile).map(\.url.absoluteString) == ["https://notexample.com/d"])82 #expect(try await history.deleteHost("WWW.NotExample.com", includingSubdomains: false) == 1)83 #expect(try await history.visitCount(profile: profile) == 0)84 #expect(try await history.visitCount() == 1)8586 #expect(try await history.deleteAll() == 1)87 #expect(try await history.visitCount() == 0)88 let indexed = try await fixture.database.sqlite.read { try $0.scalar("SELECT count(*) FROM history_fts", as: Int.self) }89 #expect(indexed == 0)90 }9192 @Test func fullTextSearchHandlesUnicode() async throws {93 let fixture = try await Fixture.make()94 let history = fixture.database.history95 let profile = fixture.profile.id96 try await history.recordVisits([97 fixture.visit("https://fr.example.com/cafe", title: "Le Café de Flore à Paris — réservation", at: second(1)),98 fixture.visit("https://de.example.com/strasse", title: "Übergrößenträger in der Straße", at: second(2)),99 fixture.visit("https://ja.example.com/tokyo", title: "東京 旅行ガイド", at: second(3)),100 fixture.visit("https://ru.example.com/moskva", title: "Москва — Путеводитель", at: second(4)),101 fixture.visit("https://ar.example.com/", title: "مرحبا بالعالم", at: second(5)),102 fixture.visit("https://emoji.example.com/", title: "Rocket 🚀 launch day", at: second(6)),103 fixture.visit("https://decomposed.example.com/", title: "Cafe\u{301} decomposed", at: second(7)),104 ])105 func hosts(_ query: String) async throws -> Set<String> {106 Set(try await history.search(query, profile: profile).compactMap { $0.url.host() })107 }108 // Accents and case are folded both ways; precomposed and decomposed forms meet.109 #expect(try await hosts("cafe") == ["fr.example.com", "decomposed.example.com"])110 #expect(try await hosts("CAFÉ") == ["fr.example.com", "decomposed.example.com"])111 #expect(try await hosts("réservation") == ["fr.example.com"])112 #expect(try await hosts("reserv") == ["fr.example.com"]) // prefix of the last word113 #expect(try await hosts("ubergrossentrager") == []) // ß is not "ss" for unicode61114 #expect(try await hosts("übergrößenträger") == ["de.example.com"])115 #expect(try await hosts("UBERGRÖSSENTRÄGER") == []) // documents the ß limitation116 #expect(try await hosts("東京") == ["ja.example.com"])117 #expect(try await hosts("москва") == ["ru.example.com"])118 #expect(try await hosts("путевод") == ["ru.example.com"])119 #expect(try await hosts("مرحبا") == ["ar.example.com"])120 #expect(try await hosts("rocket launch") == ["emoji.example.com"])121 #expect(try await hosts("🚀") == []) // no letters: nothing to search122 // Every word must match; URL parts are searchable too.123 #expect(try await hosts("paris flore") == ["fr.example.com"])124 #expect(try await hosts("paris tokyo") == [])125 #expect(try await hosts("ja.example.com/tokyo") == ["ja.example.com"])126 }127128 /// User text goes straight from the address bar into search and suggestions. None of this may throw.129 @Test func hostileSearchInputNeverThrows() async throws {130 let fixture = try await Fixture.make()131 let history = fixture.database.history132 let profile = fixture.profile.id133 try await history.recordVisits([134 fixture.visit("https://example.com/and-or-not", title: "AND OR NOT NEAR \"quoted\" (parens) star* col:on ^caret", at: second(1)),135 fixture.visit("https://example.com/plain", title: "plain words here", at: second(2)),136 ])137 let hostile = [138 "", " ", "\"", "\"\"", "\"unbalanced", "unbalanced\"", "a\"b\"c", "'", "''", "' OR 1=1 --", "\"; DROP TABLE history_urls; --",139 "*", "**", "a*", "*a", "a* b*", "^", "^a", "a^", "a:b", "title:plain", "url:", ":", "-", "-a", "a - b", "+a",140 "AND", "OR", "NOT", "NEAR", "a AND", "AND b", "a OR", "NOT a", "a NOT", "a AND AND b", "NEAR(a b, 5)", "NEAR(",141 "(", ")", "()", "(a", "a)", "((a) OR (b))", "{a}", "[a]", "a + b", "a,b", "a.b", "a/b", "a\\b", "\\", "%", "_", "%_%",142 "\u{0}", "a\u{0}b", "\n", "\t\r\n", "a\nb", "\u{FEFF}", "\u{200B}", "\u{202E}abc", "\u{301}", "e\u{301}", "\u{FFFD}",143 "🚀", "🚀🚀🚀 rocket", "👨👩👧👦", "🇨🇦", "東京", "fullwidth", "İstanbul", "Dž", "ß", "fi", "𝓯𝓪𝓷𝓬𝔂", "٣٤٥", "①②③",144 String(repeating: "a", count: 10_000), String(repeating: "\"", count: 999), String(repeating: "a ", count: 2_000),145 String(repeating: "(", count: 500), "MATCH", "history_fts", "rowid:1", "{title url}: a", "a NEAR/2 b", "\"a\" + \"b\"",146 "https://example.com/and-or-not?x=\"1\"&y=(2)#*", "javascript:alert(\"x\")", "SELECT * FROM history_urls",147 ]148 for input in hostile {149 _ = try await history.search(input, profile: profile)150 _ = try await history.suggestions(for: input, profile: profile)151 _ = try await fixture.database.bookmarks.search(input, profile: profile)152 _ = try await fixture.database.notes.search(input)153 }154 // Random soup of the characters that mean something to FTS5 and SQL.155 var generator = SystemRandomNumberGenerator()156 let alphabet = Array("ab \"'*^:-+()[]{}%_\\/.,;ANDORNOTNEAR\u{0}\né漢🚀")157 for _ in 0..<1_500 {158 let length = Int.random(in: 0...24, using: &generator)159 let input = String((0..<length).map { _ in alphabet.randomElement(using: &generator)! })160 _ = try await history.search(input, profile: profile)161 _ = try await history.suggestions(for: input, profile: profile)162 }163 // Operators are plain words, not syntax.164 #expect(try await history.search("AND", profile: profile).count == 1)165 #expect(try await history.search("NOT plain", profile: profile).isEmpty)166 #expect(try await history.search("\"quoted\" (parens)", profile: profile).count == 1)167 #expect(try await history.search("plain OR quoted", profile: profile).isEmpty)168 #expect(try await history.visitCount() == 2)169 }170171 @Test func ftsQueryBuilder() {172 #expect(FTSQuery.make("") == nil)173 #expect(FTSQuery.make(" \"*^-() ") == nil)174 #expect(FTSQuery.make("hello") == "\"hello\"*")175 #expect(FTSQuery.make("Hello World") == "\"Hello\"* \"World\"*")176 #expect(FTSQuery.make("a\"b") == "\"a\"* \"b\"*")177 #expect(FTSQuery.make("github.com/apple") == "\"github\"* \"com\"* \"apple\"*")178 #expect(FTSQuery.make("café", prefix: false) == "\"café\"")179 #expect(FTSQuery.tokens(in: String(repeating: "x ", count: 50)).count == 12)180 }181182 @Test func frecencyOrdersSuggestions() async throws {183 let fixture = try await Fixture.make()184 let history = fixture.database.history185 let profile = fixture.profile.id186 let now = day(400)187 func visits(_ address: String, _ title: String, count: Int, daysAgo: Double, _ transition: NavigationEntry.Transition = .link) -> [NavigationEntry] {188 (0..<count).map { fixture.visit(address, title: title, at: now.addingTimeInterval(-daysAgo * 86_400 - Double($0) * 60), transition: transition) }189 }190 try await history.recordVisits(191 visits("https://docs.example.com/daily", "Docs daily", count: 12, daysAgo: 1)192 + visits("https://docs.example.com/once-today", "Docs once today", count: 1, daysAgo: 0.1)193 + visits("https://docs.example.com/old-favourite", "Docs old favourite", count: 12, daysAgo: 240)194 + visits("https://docs.example.com/typed", "Docs typed", count: 1, daysAgo: 2, .typed)195 + visits("https://docs.example.com/linked", "Docs linked", count: 1, daysAgo: 2, .link)196 + visits("https://docs.example.com/redirect", "Docs redirect", count: 1, daysAgo: 2, .redirect)197 + visits("https://docs.example.com/reloaded", "Docs reloaded", count: 5, daysAgo: 0.5, .reload)198 )199 let ranked = try await history.suggestions(for: "docs", profile: profile, limit: 10)200 #expect(ranked.map(\.page.url.lastPathComponent) == ["daily", "typed", "once-today", "linked", "redirect", "old-favourite", "reloaded"])201 // Scores are strictly ordered and the score explains the order.202 #expect(zip(ranked, ranked.dropFirst()).allSatisfy { $0.score >= $1.score })203 #expect(try await history.topPages(profile: profile, limit: 3).map(\.url.lastPathComponent) == ["daily", "typed", "once-today"])204 // Pages that were only reloaded never make it to the top sites.205 #expect(try await history.topPages(profile: profile, limit: 50).contains { $0.url.lastPathComponent == "reloaded" } == false)206207 // The stored score decodes to the decayed visit count: 12 link visits 240 days (8 half-lives) ago.208 let old = try #require(ranked.first { $0.page.url.lastPathComponent == "old-favourite" })209 let effective = Frecency.effectiveVisits(stored: old.page.frecency, now: now)210 #expect(abs(effective - 12.0 / 256.0) < 0.001)211 let daily = try #require(ranked.first)212 #expect(abs(Frecency.effectiveVisits(stored: daily.page.frecency, now: now) - 12 * pow(2, -1.0 / 30)) < 0.01)213214 // Recency beats raw count when a new visit arrives: one visit now lifts the old favourite above "linked".215 try await history.recordVisit(fixture.visit("https://docs.example.com/old-favourite", title: "Docs old favourite", at: now))216 let after = try await history.suggestions(for: "docs", profile: profile, limit: 10).map(\.page.url.lastPathComponent)217 #expect(after.firstIndex(of: "old-favourite")! < after.firstIndex(of: "linked")!)218 // The incremental update equals a full recomputation from the visits.219 let incremental = try #require(try await history.page(for: url("https://docs.example.com/old-favourite"), profile: profile)).frecency220 try await fixture.database.sqlite.transaction { try HistorySQL.recomputeFrecency($0, where: "1 = 1", []) }221 let recomputed = try #require(try await history.page(for: url("https://docs.example.com/old-favourite"), profile: profile)).frecency222 #expect(abs(incremental - recomputed) < 1e-9)223 }224225 @Test func hostPrefixBoostAndProfileIsolation() async throws {226 let fixture = try await Fixture.make()227 let history = fixture.database.history228 let profile = fixture.profile.id229 let other = Profile(name: "Other", createdAt: day())230 try await fixture.database.profiles.save(other)231 // "github" appears in a much-visited page of another host, and once as the host itself.232 try await history.recordVisits((0..<3).map { fixture.visit("https://blog.example.com/why-github-won", title: "Why GitHub won", at: second(Double($0))) })233 try await history.recordVisit(fixture.visit("https://www.github.com/apple/swift", title: "apple/swift", at: second(0)))234 try await history.recordVisit(NavigationEntry(profileID: other.id, url: url("https://github.example.net/secret"), title: "github secret", visitedAt: second(5)))235236 let suggestions = try await history.suggestions(for: "gith", profile: profile)237 #expect(suggestions.map { $0.page.url.host() } == ["www.github.com", "blog.example.com"])238 #expect(suggestions.map(\.matchesHostPrefix) == [true, false])239 // A full scheme and www. do not defeat host matching.240 #expect(try await history.suggestions(for: "https://www.gith", profile: profile).first?.matchesHostPrefix == true)241 // Multi-word input narrows by title and URL words.242 #expect(try await history.suggestions(for: "github won", profile: profile).map { $0.page.url.host() } == ["blog.example.com"])243 #expect(try await history.suggestions(for: "apple sw", profile: profile).map { $0.page.url.host() } == ["www.github.com"])244 #expect(try await history.suggestions(for: "", profile: profile).isEmpty)245 #expect(try await history.suggestions(for: "zzz", profile: profile).isEmpty)246 // Another profile's history never leaks into suggestions or search.247 #expect(try await history.suggestions(for: "secret", profile: profile).isEmpty)248 #expect(try await history.search("secret", profile: profile).isEmpty)249 #expect(try await history.suggestions(for: "secret", profile: other.id).count == 1)250 }251252 @Test func searchIndexStaysConsistentThroughCascades() async throws {253 let fixture = try await Fixture.make()254 let database = fixture.database255 let doomed = Profile(name: "Doomed", createdAt: day())256 try await database.profiles.save(doomed)257 try await database.history.recordVisits((0..<50).map {258 NavigationEntry(profileID: doomed.id, url: url("https://doomed.example.com/\($0)"), title: "Doomed page \($0)", visitedAt: second(Double($0)))259 })260 try await database.history.recordVisits((0..<50).map { fixture.visit("https://kept.example.com/\($0)", title: "Kept page \($0)", at: second(Double($0))) })261 // Deleting the profile cascades to its URLs; the delete trigger must remove them from the FTS index.262 try await database.profiles.delete(doomed.id)263 let counts = try await database.sqlite.write { connection -> (Int, Int) in264 // FTS5's own consistency check between the index and the content table; throws when they differ.265 try connection.execute("INSERT INTO history_fts(history_fts, rank) VALUES ('integrity-check', 1)")266 return (try connection.scalar("SELECT count(*) FROM history_urls", as: Int.self) ?? -1,267 try connection.scalar("SELECT count(*) FROM history_fts WHERE history_fts MATCH '\"doomed\"'", as: Int.self) ?? -1)268 }269 #expect(counts.0 == 50)270 #expect(counts.1 == 0)271 #expect(try await database.history.search("kept page", profile: fixture.profile.id, limit: 100).count == 50)272 }273274 /// 100 000 distinct URLs, 150 000 visits, on a file database: measures the omnibox query. Reports numbers.275 @Test func suggestionBenchmarkOn100kRows() async throws {276 let scratch = try ScratchDirectory()277 let database = try await NavigatorDatabase(url: scratch.databaseURL)278 let fixture = try await Fixture.make(in: database)279 let profile = fixture.profile.id280 let words = ["swift", "apple", "kernel", "orbit", "lunar", "garden", "recipe", "travel", "music", "finance", "weather",281 "science", "history", "design", "camera", "privacy", "browser", "network", "garage", "github", "golang",282 "python", "rust", "linux", "docker", "kubernetes", "postgres", "sqlite", "review", "manual", "guide"]283 let tlds = ["com", "org", "net", "io", "dev", "ca", "fr"]284 var generator = SplitMix(seed: 42)285 let now = Date.now286 let clock = ContinuousClock()287 let urlCount = 100_000288 let insertTime = try await clock.measure {289 for batch in stride(from: 0, to: urlCount, by: 10_000) {290 var entries: [NavigationEntry] = []291 entries.reserveCapacity(15_000)292 for index in batch..<(batch + 10_000) {293 let host = "\(words[Int(generator.next() % 31)])\(index % 4_000).\(tlds[Int(generator.next() % 7)])"294 let a = words[Int(generator.next() % 31)], b = words[Int(generator.next() % 31)], c = words[Int(generator.next() % 31)]295 let address = url("https://\(index % 3 == 0 ? "www." : "")\(host)/\(a)/\(b)-\(index)")296 let visits = index % 2 == 0 ? 2 : 1297 for visit in 0..<visits {298 entries.append(NavigationEntry(profileID: profile, url: address, title: "\(a.capitalized) \(b) \(c) — page \(index)",299 visitedAt: now.addingTimeInterval(-Double(generator.next() % 31_536_000) - Double(visit)),300 transition: generator.next() % 10 == 0 ? .typed : .link))301 }302 }303 try await database.history.recordVisits(entries)304 }305 }306 let rows = try await database.sqlite.read { connection in307 (try connection.scalar("SELECT count(*) FROM history_urls", as: Int.self) ?? 0,308 try connection.scalar("SELECT count(*) FROM history_visits", as: Int.self) ?? 0)309 }310 #expect(rows.0 == urlCount)311 #expect(rows.1 == 150_000)312 let size = (try FileManager.default.attributesOfItem(atPath: scratch.databaseURL.path)[.size] as? Int) ?? 0313 print("[benchmark] history: \(rows.0) URLs, \(rows.1) visits inserted in \(format(milliseconds(insertTime))) ms, database \(size / 1_048_576) MiB")314315 // From a one-letter prefix that matches a large share of the table to a selective multi-word query.316 for input in ["s", "sw", "swi", "swift", "git", "github", "swift apple", "sqlite gui", "github12", "https://www.rust", "page 4242", "zzzzqq", "com"] {317 var samples: [Double] = []318 var count = 0319 for _ in 0..<15 {320 samples.append(milliseconds(try await clock.measure {321 count = try await database.history.suggestions(for: input, profile: profile, limit: 8).count322 }))323 }324 samples.sort()325 print("[benchmark] suggestions(\"\(input)\") → \(count) rows: median \(format(samples[7])) ms, worst \(format(samples[14])) ms")326 }327 var searchSamples: [Double] = []328 for _ in 0..<9 {329 searchSamples.append(milliseconds(try await clock.measure { _ = try await database.history.search("swift guide", profile: profile, limit: 50) }))330 }331 searchSamples.sort()332 print("[benchmark] search(\"swift guide\", limit 50): median \(format(searchSamples[4])) ms")333334 // The result is right, not just fast: best-first, and every row really matches.335 let top = try await database.history.suggestions(for: "swift apple", profile: profile, limit: 8)336 #expect(top.count == 8)337 #expect(zip(top, top.dropFirst()).allSatisfy { $0.score >= $1.score })338 #expect(top.allSatisfy { ($0.page.title + " " + $0.page.url.absoluteString).lowercased().contains("swift") })339 #expect(top.allSatisfy { ($0.page.title + " " + $0.page.url.absoluteString).lowercased().contains("apple") })340341 let retention = try await clock.measure {342 _ = try await database.lifecycle.applyHistoryRetention(days: 180, now: now)343 }344 let remaining = try await database.history.visitCount()345 print("[benchmark] retention (keep 180 days) removed \(150_000 - remaining) visits in \(format(milliseconds(retention))) ms")346 #expect(remaining > 0 && remaining < 150_000)347 await database.close()348 }349}350351/// Deterministic generator so the benchmark data is the same on every run.352struct SplitMix {353 var state: UInt64354 init(seed: UInt64) { state = seed }355 mutating func next() -> UInt64 {356 state &+= 0x9E37_79B9_7F4A_7C15357 var z = state358 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9359 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB360 return z ^ (z >> 31)361 }362}363