Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Keyboard9// File : Shared/Tests/PredictionCoreTests/PredictionEngineTests.swift10// Description : Engine behaviour: typo corpora FR-CA/EN/ES, homophones,11// guards, ranking, casing, cache, cancellation.12// Module : PredictionCoreTests13// Repository : https://git.spboucher.ai/sp-keyboard14// Created : 2026-12-0115// Last Modified : 2026-12-0116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import XCTest90@testable import PredictionCore9192final class PredictionEngineTests: XCTestCase {93 private func predict(_ engine: PredictionEngine, _ word: String, _ language: LexiconLanguage, previous: [String] = [],94 start: Bool = false, autocorrect: Bool = true, geometry: KeyGeometry = .qwerty) async -> PredictionResult {95 await engine.predict(PredictionQuery(currentWord: word, previousWords: previous, language: language, geometry: geometry,96 isSentenceStart: start, autocorrectionEnabled: autocorrect))97 }9899 // MARK: Touch model100101 func testNextLetterWeights() async throws {102 let engine = try await makeEngine()103 let afterBonjou = await engine.nextLetterWeights(prefix: "bonjou", language: .french)104 XCTAssertGreaterThan(afterBonjou["r"] ?? 0, 0.95, "« bonjou » continues with r")105 let afterQ = await engine.nextLetterWeights(prefix: "q", language: .french)106 XCTAssertGreaterThan(afterQ["u"] ?? 0, 0.9)107 XCTAssertEqual(afterQ.values.reduce(0, +), 1, accuracy: 1e-6)108 // Accents are folded: « él » and « el » read the same part of the lexicon.109 let accented = await engine.nextLetterWeights(prefix: "él", language: .french)110 let plain = await engine.nextLetterWeights(prefix: "el", language: .french)111 XCTAssertEqual(accented, plain)112 XCTAssertFalse(plain.isEmpty)113 let empty = await engine.nextLetterWeights(prefix: "", language: .french)114 XCTAssertTrue(empty.isEmpty)115 let nonsense = await engine.nextLetterWeights(prefix: "zzqxj", language: .french)116 XCTAssertTrue(nonsense.isEmpty)117 let unloaded = try await makeEngine([.english]).nextLetterWeights(prefix: "bon", language: .french)118 XCTAssertTrue(unloaded.isEmpty)119 }120121 // MARK: Typo corpora (measured accuracy is printed; thresholds sit a little below the measured values)122123 func testTypoCorpora() async throws {124 let engine = try await makeEngine()125 let sets: [(LexiconLanguage, [Typo], Double)] = [(.french, Corpus.french, 0.9), (.english, Corpus.english, 0.9), (.spanish, Corpus.spanish, 0.9)]126 for (language, corpus, floor) in sets {127 let typos = corpus.filter { $0.kind != "ok" }128 var fixed = 0, offered = 0, wrong: [String] = [], missed: [String] = []129 for typo in typos {130 let result = await predict(engine, typo.typed, language)131 XCTAssertLessThanOrEqual(result.suggestions.count, 3)132 XCTAssertEqual(Set(result.suggestions.map(\.text)).count, result.suggestions.count, "deduplicated")133 if result.suggestions.contains(where: { $0.text == typo.expected }) { offered += 1 }134 if result.autocorrection?.text == typo.expected {135 fixed += 1136 } else if let other = result.autocorrection {137 wrong.append("\(typo.typed)→\(other.text)")138 } else {139 missed.append(typo.typed)140 }141 }142 let rate = Double(fixed) / Double(typos.count), offeredRate = Double(offered) / Double(typos.count)143 print("ACCURACY \(language.rawValue): \(typos.count) typos, auto-corrected \(fixed) (\(Int((rate * 100).rounded())) %), offered in the bar \(offered) (\(Int((offeredRate * 100).rounded())) %), wrong corrections \(wrong), left alone \(missed)")144 XCTAssertGreaterThanOrEqual(rate, floor, "\(language)")145 XCTAssertGreaterThanOrEqual(offeredRate, 0.95, "\(language)")146 XCTAssertTrue(wrong.isEmpty, "\(language) wrong corrections: \(wrong)")147 }148 }149150 func testValidWordsAndHomophonesAreNeverCorrected() async throws {151 let engine = try await makeEngine()152 for (language, words) in [(LexiconLanguage.french, Corpus.validFrench), (.english, Corpus.validEnglish), (.spanish, Corpus.validSpanish)] {153 for word in words {154 let result = await predict(engine, word, language)155 XCTAssertNil(result.autocorrection, "\(language) \(word) → \(result.autocorrection?.text ?? "")")156 XCTAssertFalse(result.suggestions.contains { $0.kind == .verbatim }, "\(word) is a word: no verbatim slot")157 }158 }159 // The other member of a homophone pair is offered, never imposed.160 let a = await predict(engine, "a", .french)161 XCTAssertTrue(a.suggestions.contains { $0.text == "à" })162 let ou = await predict(engine, "ou", .french)163 XCTAssertTrue(ou.suggestions.contains { $0.text == "où" })164 let el = await predict(engine, "el", .spanish)165 XCTAssertTrue(el.suggestions.contains { $0.text == "él" })166 }167168 func testAccentRestorationRanksFirst() async throws {169 let engine = try await makeEngine()170 for (typed, expected, language) in [("ecole", "école", LexiconLanguage.french), ("nino", "niño", .spanish), ("deja", "déjà", .french), ("manana", "mañana", .spanish)] {171 let result = await predict(engine, typed, language)172 XCTAssertEqual(result.autocorrection?.text, expected)173 XCTAssertEqual(result.suggestions.first?.kind, .verbatim)174 XCTAssertEqual(result.suggestions.dropFirst().first?.text, expected, "the fix sits right after the verbatim word")175 }176 }177178 // MARK: False-positive guards179180 func testProperNounsAndUnusualTokensAreLeftAlone() async throws {181 let engine = try await makeEngine()182 let tokens = ["Tremblay", "Gagnonn", "Bonjuor", "Khaelor", "iPhone", "macOS", "NASA", "BONJUOR", "https://spboucher.ai", "www.example.com",183 "nom@example.com", "user_name", "snake_case", "camelCase", "v1.2.3", "42", "3h30", "h2o", "#tag", "@pseudo",184 "x=1", "foo()", "a/b", "C:\\temp", "50%", "$19.99", "`code`", "arr[0]"]185 for token in tokens {186 for language in LexiconLanguage.allCases {187 let result = await predict(engine, token, language)188 XCTAssertNil(result.autocorrection, "\(token) (\(language)) → \(result.autocorrection?.text ?? "")")189 }190 }191 // …but the same typo is fixed where a capital is expected.192 let start = await predict(engine, "Bonjuor", .french, start: true)193 XCTAssertEqual(start.autocorrection?.text, "Bonjour")194 let off = await predict(engine, "bonjuor", .french, autocorrect: false)195 XCTAssertNil(off.autocorrection)196 XCTAssertTrue(off.suggestions.contains { $0.text == "bonjour" }, "still offered when autocorrection is off")197 }198199 func testProfanityIsNeverAnAutocorrectionTarget() async throws {200 let engine = try await makeEngine()201 for (typed, language) in [("fuvk", LexiconLanguage.english), ("shitt", .english), ("merdr", .french), ("putian", .french), ("mierdaa", .spanish)] {202 let result = await predict(engine, typed, language)203 if let fix = result.autocorrection {204 XCTAssertFalse(Profanity.folded.contains(TextFolding.fold(fix.text)), "\(typed) → \(fix.text)")205 }206 }207 // Typed on purpose, it is a word and stays.208 let kept = await predict(engine, "merde", .french)209 XCTAssertNil(kept.autocorrection)210 }211212 func testOutOfLexiconWordsMeasuredFalsePositiveRate() async throws {213 let engine = try await makeEngine()214 // Legitimate lowercase tokens the 30k lexicons do not contain: brand-like words, jargon, rare vocabulary.215 let samples: [(LexiconLanguage, [String])] = [216 (.french, ["blockchain", "podcast", "tiktok", "wordle", "hypothécation", "zoom", "figma", "kubernetes", "amortissement", "hétéroscédasticité",217 "cointégration", "backtest", "dataset", "scraping", "frontend", "plex", "valoplex", "maclustr", "louka", "immoka"]),218 (.english, ["blockchain", "podcast", "tiktok", "wordle", "heteroskedasticity", "zoom", "figma", "kubernetes", "backtest", "dataset",219 "scraping", "frontend", "cointegration", "maclustr", "regex", "async", "webhook", "xcode", "swiftui", "testflight"]),220 (.spanish, ["blockchain", "podcast", "tiktok", "wordle", "zoom", "figma", "kubernetes", "backtest", "dataset", "frontend",221 "criptomoneda", "heterocedasticidad", "cointegración", "maclustr", "regex", "webhook", "xcode", "testflight", "wasap", "finde"]),222 ]223 var total = 0, changed: [String] = []224 for (language, words) in samples {225 for word in words {226 total += 1227 if let fix = (await predict(engine, word, language)).autocorrection { changed.append("\(language.rawValue):\(word)→\(fix.text)") }228 }229 }230 print("FALSE POSITIVES on out-of-lexicon words: \(changed.count)/\(total) \(changed)")231 XCTAssertLessThanOrEqual(Double(changed.count) / Double(total), 0.25)232 }233234 // MARK: User dictionaries235236 func testPersonalLearnedAndSupplementaryWords() async throws {237 let engine = try await makeEngine([.french, .english])238 let before = await predict(engine, "bonjoor", .french)239 XCTAssertEqual(before.autocorrection?.text, "bonjour")240241 await engine.setPersonalWords(["Khaelor", "bonjoor", " ", "two words", "MacLustr"])242 let personal = await predict(engine, "bonjoor", .french)243 XCTAssertNil(personal.autocorrection, "a personal word is always valid")244 let prefix = await predict(engine, "khae", .french)245 XCTAssertEqual(prefix.suggestions.first { $0.kind == .personal }?.text, "Khaelor")246 let lower = await predict(engine, "khaelor", .english)247 XCTAssertNil(lower.autocorrection)248249 await engine.setLearnedWords(["valoplex": 4, "immoka": 1])250 let learned = await predict(engine, "valop", .french)251 XCTAssertTrue(learned.suggestions.contains { $0.text == "valoplex" && $0.kind == .personal })252 let learnedExact = await predict(engine, "valoplex", .french)253 XCTAssertNil(learnedExact.autocorrection)254255 await engine.setSupplementary(["omw": "On my way!", "adr": "123, rue Fictive, Gatineau"])256 let shortcut = await predict(engine, "omw", .english)257 XCTAssertEqual(shortcut.suggestions.first, Suggestion(text: "On my way!", kind: .shortcut, score: 100))258 XCTAssertNil(shortcut.autocorrection, "a shortcut is inserted only when the user taps it")259260 await engine.setPersonalWords([])261 let after = await predict(engine, "bonjoor", .french)262 XCTAssertEqual(after.autocorrection?.text, "bonjour", "removing the personal word re-enables the correction (cache invalidated)")263 }264265 // MARK: Ranking, casing, context266267 func testCompletionKeepsTheTypedCase() async throws {268 let engine = try await makeEngine([.french])269 let lower = await predict(engine, "bon", .french)270 XCTAssertEqual(lower.suggestions.first?.text, "bonjour")271 XCTAssertEqual(lower.suggestions.first?.kind, .completion)272 let first = await predict(engine, "Bon", .french)273 XCTAssertEqual(first.suggestions.first?.text, "Bonjour")274 let upper = await predict(engine, "BON", .french)275 XCTAssertEqual(upper.suggestions.first?.text, "BONJOUR")276 let start = await predict(engine, "bon", .french, start: true)277 XCTAssertEqual(start.suggestions.first?.text, "Bonjour")278 XCTAssertNil(lower.autocorrection)279 }280281 func testContextChangesTheRanking() async throws {282 let engine = try await makeEngine([.french, .english])283 let afterJe = await predict(engine, "s", .french, previous: ["je"])284 XCTAssertEqual(afterJe.suggestions.first?.text, "suis")285 let afterIls = await predict(engine, "s", .french, previous: ["ils"])286 XCTAssertEqual(afterIls.suggestions.first?.text, "sont")287 let english = await predict(engine, "y", .english, previous: ["thank"])288 XCTAssertEqual(english.suggestions.first?.text, "you")289 }290291 func testNextWordPredictions() async throws {292 let engine = try await makeEngine()293 let je = await predict(engine, "", .french, previous: ["je"])294 XCTAssertEqual(je.suggestions.map(\.text), ["suis", "vais", "ne"])295 XCTAssertTrue(je.suggestions.allSatisfy { $0.kind == .nextWord })296 XCTAssertNil(je.autocorrection)297 let start = await predict(engine, "", .french, start: true)298 XCTAssertEqual(start.suggestions.first?.text, "Je")299 let twoWords = await predict(engine, "", .english, previous: ["let", "me"])300 XCTAssertEqual(twoWords.suggestions.first?.text, "know")301 let unknownPrevious = await predict(engine, "", .spanish, previous: ["zzzz"])302 XCTAssertEqual(unknownPrevious.suggestions.count, 3, "generic fallback")303 let typographic = await predict(engine, "", .french, previous: ["c’est"])304 XCTAssertEqual(typographic.suggestions.first?.text, "bon")305 }306307 func testFrenchElisionAndEnglishContractions() async throws {308 let engine = try await makeEngine([.french, .english])309 let jai = await predict(engine, "j'a", .french)310 XCTAssertEqual(jai.suggestions.first?.text, "j'ai")311 let curly = await predict(engine, "l’ecole", .french)312 XCTAssertEqual(curly.autocorrection?.text, "l'école")313 let capital = await predict(engine, "L'ecole", .french, start: true)314 XCTAssertEqual(capital.autocorrection?.text, "L'école")315 let stub = await predict(engine, "qu'", .french)316 XCTAssertEqual(stub, .empty)317 let pronoun = await predict(engine, "i", .english)318 XCTAssertEqual(pronoun.autocorrection?.text, "I")319 let im = await predict(engine, "im", .english)320 XCTAssertEqual(im.autocorrection?.text, "I'm")321 let dont = await predict(engine, "dont", .english)322 XCTAssertEqual(dont.autocorrection?.text, "don't")323 let london = await predict(engine, "london", .english)324 XCTAssertEqual(london.suggestions.first?.text, "London")325 XCTAssertNil(london.autocorrection, "proper nouns are offered, not imposed")326 }327328 func testGeometryInfluencesNeighbourCost() async throws {329 let engine = try await makeEngine([.french])330 // q and a are neighbours on QWERTY (q above a), z and a on AZERTY.331 let azerty = await predict(engine, "mzison", .french, geometry: .azerty)332 XCTAssertEqual(azerty.autocorrection?.text, "maison")333 let qwerty = await predict(engine, "mqison", .french, geometry: .qwerty)334 XCTAssertEqual(qwerty.autocorrection?.text, "maison")335 }336337 func testNonsenseAndOversizedInput() async throws {338 let engine = try await makeEngine([.english])339 let nonsense = await predict(engine, "xqzkvw", .english)340 XCTAssertNil(nonsense.autocorrection)341 let long = await predict(engine, String(repeating: "a", count: 500), .english)342 XCTAssertEqual(long, .empty)343 let emoji = await predict(engine, "👍🏽", .english)344 XCTAssertEqual(emoji, .empty)345 let punctuation = await predict(engine, "...", .english)346 XCTAssertEqual(punctuation, .empty)347 }348349 // MARK: Lifecycle350351 func testUnloadedLanguageAndMissingFiles() async throws {352 let engine = PredictionEngine(provider: DirectoryLexiconProvider(directory: repositoryLexicons))353 let unloaded = await predict(engine, "bonjuor", .french)354 XCTAssertEqual(unloaded, .empty)355 let loadedBefore = await engine.isLoaded(.french)356 XCTAssertFalse(loadedBefore)357 try await engine.load(.french)358 try await engine.load(.french) // idempotent359 let loaded = await engine.isLoaded(.french)360 XCTAssertTrue(loaded)361 let other = await predict(engine, "helo", .english)362 XCTAssertEqual(other, .empty, "only the loaded language answers")363 await engine.unload(.french)364 let afterUnload = await predict(engine, "bonjuor", .french)365 XCTAssertEqual(afterUnload, .empty)366367 let missing = PredictionEngine(provider: MemoryLexiconProvider([:]))368 do {369 try await missing.load(.spanish)370 XCTFail("expected a throw")371 } catch {372 XCTAssertEqual(error as? LexiconError, .missingResource(.spanish, .words))373 }374 let malformed = PredictionEngine(provider: MemoryLexiconProvider(["en.lex": "no tab at all"]))375 do {376 try await malformed.load(.english)377 XCTFail("expected a throw")378 } catch {379 XCTAssertEqual(error as? LexiconError, .malformed(.english))380 }381 let stillUnloaded = await malformed.isLoaded(.english)382 XCTAssertFalse(stillUnloaded)383384 // A lexicon without its bigram file still works (ranking by frequency only).385 let noBigrams = PredictionEngine(provider: MemoryLexiconProvider(["fr.lex": "bonjour\t900\nbonne\t500\nmerci\t800\n"]))386 try await noBigrams.load(.french)387 let completion = await predict(noBigrams, "bo", .french)388 XCTAssertEqual(completion.suggestions.first { $0.kind == .completion }?.text, "bonjour")389 let next = await predict(noBigrams, "", .french, previous: ["je"])390 XCTAssertEqual(next, .empty)391 }392393 func testCacheIsBoundedAndCanBeDisabled() async throws {394 let engine = try await makeEngine([.french], cacheLimit: 4)395 for prefix in ["a", "b", "c", "d", "e", "f", "g", "h", "bo", "bon", "bonj", "me", "mer"] {396 _ = await predict(engine, prefix, .french)397 let count = await engine.cachedResultCount398 XCTAssertLessThanOrEqual(count, 4)399 }400 let first = await predict(engine, "mer", .french)401 let second = await predict(engine, "mer", .french)402 XCTAssertEqual(first, second, "a cached answer is the same answer")403 await engine.trimMemory()404 let afterTrim = await engine.cachedResultCount405 XCTAssertEqual(afterTrim, 0)406407 let uncached = try await makeEngine([.french], cacheLimit: 0)408 _ = await predict(uncached, "bon", .french)409 let none = await uncached.cachedResultCount410 XCTAssertEqual(none, 0)411 }412413 func testTrimMemoryKeepsOnlyTheLastUsedLanguage() async throws {414 let engine = try await makeEngine()415 _ = await predict(engine, "hel", .english)416 _ = await predict(engine, "bon", .french)417 await engine.trimMemory()418 let french = await engine.isLoaded(.french), english = await engine.isLoaded(.english), spanish = await engine.isLoaded(.spanish)419 XCTAssertTrue(french)420 XCTAssertFalse(english)421 XCTAssertFalse(spanish)422 let footprint = await engine.footprint(of: .french)423 XCTAssertGreaterThan(footprint.words, 29_000)424 let gone = await engine.footprint(of: .english)425 XCTAssertEqual(gone.words, 0)426 }427428 func testCancelledTaskGetsAnEmptyResult() async throws {429 let engine = try await makeEngine([.french], cacheLimit: 0)430 let task = Task { () -> PredictionResult in431 withUnsafeCurrentTask { $0?.cancel() }432 return await engine.predict(PredictionQuery(currentWord: "bonjuor", language: .french))433 }434 let cancelled = await task.value435 XCTAssertEqual(cancelled, .empty)436 // Obsolete requests cancelled while queued behind the actor never produce a stale bar.437 let tasks = (0..<40).map { index in438 Task { await engine.predict(PredictionQuery(currentWord: "mainetnan" + String(repeating: "t", count: index % 3), language: .french)) }439 }440 for task in tasks.dropLast() { task.cancel() }441 var answered = 0442 for task in tasks where await task.value != .empty { answered += 1 }443 XCTAssertGreaterThanOrEqual(answered, 1)444 let live = await engine.predict(PredictionQuery(currentWord: "bonjuor", language: .french))445 XCTAssertEqual(live.autocorrection?.text, "bonjour", "the engine is intact after cancellations")446 }447448 // MARK: Measured latency and memory (numbers are printed; the assertion is deliberately loose)449450 func testBenchmark() async throws {451 let engine = try await makeEngine(LexiconLanguage.allCases, cacheLimit: 0)452 let loadStart = ContinuousClock.now453 let cold = PredictionEngine(provider: DirectoryLexiconProvider(directory: repositoryLexicons))454 try await cold.load(.french)455 let loadTime = ContinuousClock.now - loadStart456 var queries: [PredictionQuery] = []457 for (language, corpus) in [(LexiconLanguage.french, Corpus.french), (.english, Corpus.english), (.spanish, Corpus.spanish)] {458 for typo in corpus {459 // Every keystroke of the word, as the keyboard would ask.460 for length in 1...typo.typed.count {461 queries.append(PredictionQuery(currentWord: String(typo.typed.prefix(length)), previousWords: ["je"], language: language))462 }463 queries.append(PredictionQuery(currentWord: "", previousWords: [typo.expected], language: language))464 }465 }466 var samples: [Double] = []467 samples.reserveCapacity(queries.count)468 let clock = ContinuousClock()469 for query in queries {470 let start = clock.now471 _ = await engine.predict(query)472 let elapsed = clock.now - start473 samples.append(Double(elapsed.components.attoseconds) / 1e15 + Double(elapsed.components.seconds) * 1000)474 }475 samples.sort()476 let p50 = samples[samples.count / 2], p95 = samples[Int(Double(samples.count) * 0.95)], worst = samples.last ?? 0477 var footprint: [String] = []478 for language in LexiconLanguage.allCases {479 let size = await engine.footprint(of: language)480 footprint.append("\(language.rawValue) \(size.words) words ≈ \(size.bytes / 1024) KB")481 }482 #if DEBUG483 let build = "debug"484 #else485 let build = "release"486 #endif487 let loadMs = Double(loadTime.components.attoseconds) / 1e15 + Double(loadTime.components.seconds) * 1000488 print(String(format: "BENCHMARK (%@) predict over %d keystroke queries: p50 %.2f ms, p95 %.2f ms, max %.2f ms; cold load fr %.1f ms; index %@",489 build, samples.count, p50, p95, worst, loadMs, footprint.joined(separator: ", ")))490 #if !DEBUG491 XCTAssertLessThan(p95, 50)492 #endif493 }494}495