SPB Git

Repository Public License

MemoryIndexTests.swift 34.0 KB 473 lines swift

1import Foundation2import NavigatorCore3import Persistence4import Testing5@testable import MemoryEngine67@Suite struct MemoryChunkingTests {8    static let sentences = (1...60).map { "Sentence number \($0) talks about topic \($0 % 7) in some detail." }910    @Test func chunksKeepSentencesWholeAndOverlap() {11        let text = Self.sentences.joined(separator: " ")12        let chunks = MemoryChunker.chunks(of: text, target: 400, overlap: 120, maximum: 600)13        #expect(chunks.count > 5)14        for chunk in chunks {15            #expect(chunk.count <= 600 && !chunk.isEmpty)16            #expect(chunk.hasPrefix("Sentence number") && chunk.hasSuffix("detail."), "cut inside a sentence: \(chunk.prefix(40))…\(chunk.suffix(20))")17        }18        // Every sentence is in some chunk, and neighbours share at least one sentence.19        for sentence in Self.sentences { #expect(chunks.contains { $0.contains(sentence) }) }20        for index in 1..<chunks.count {21            let opening = String(chunks[index].prefix { $0 != "." }) + "."22            #expect(chunks[index - 1].hasSuffix(opening) || chunks[index - 1].contains(opening + " "), "no overlap between chunk \(index - 1) and \(index)")23            #expect(chunks[index] != chunks[index - 1])24        }25        #expect(chunks.reduce(0) { $0 + $1.count } < text.count * 2)26        #expect(MemoryChunker.chunks(of: text, target: 400, overlap: 0, maximum: 600).joined(separator: " ") == text)27    }2829    @Test func paragraphsWhitespaceAndDegenerateInput() {30        #expect(MemoryChunker.chunks(of: "").isEmpty)31        #expect(MemoryChunker.chunks(of: " \n\n \t\n").isEmpty)32        #expect(MemoryChunker.chunks(of: "One short line.") == ["One short line."])33        #expect(MemoryChunker.paragraphs(of: "a   b\t c\nsame paragraph\n\n\n  second  \r\n\r\nthird") == ["a b c same paragraph", "second", "third"])34        // A chunk prefers to stop at a paragraph end once it is half full.35        let first = Self.sentences.prefix(4).joined(separator: " "), second = Self.sentences.suffix(4).joined(separator: " ")36        let chunks = MemoryChunker.chunks(of: first + "\n\n" + second, target: 400, overlap: 0, maximum: 600)37        #expect(chunks == [first, second])38        // Text with no sentence boundary and no space at all is still cut to the maximum.39        let blob = String(repeating: "x", count: 5_000)40        let pieces = MemoryChunker.chunks(of: blob, target: 300, overlap: 50, maximum: 400)41        #expect(pieces.allSatisfy { $0.count <= 400 } && pieces.joined().count == 5_000)42        let long = (0..<400).map { "word\($0)" }.joined(separator: " ")43        #expect(MemoryChunker.chunks(of: long, target: 300, overlap: 0, maximum: 400).allSatisfy { $0.count <= 400 && !$0.hasPrefix(" ") })44        #expect(MemoryChunker.chunks(of: "Ünïcödé 文字 🚀. Deuxième phrase ! Третье предложение?", target: 50, overlap: 0, maximum: 60).count >= 1)45    }46}4748@Suite struct MemoryRankingTests {49    @Test func reciprocalRankFusion() {50        let fused = MemoryRanking.fuse([[1, 2, 3, 4], [3, 5, 1]], k: 60)51        #expect(fused.map(\.id) == [1, 3, 2, 5, 4])52        #expect(abs(fused[0].score - (1.0 / 61 + 1.0 / 63)) < 1e-12)53        #expect(abs(fused[1].score - (1.0 / 63 + 1.0 / 61)) < 1e-12)54        #expect(abs(fused[4].score - 1.0 / 64) < 1e-12)55        // In both lists beats first in one.56        #expect(MemoryRanking.fuse([[9, 1], [8, 1]]).first?.id == 1)57        #expect(MemoryRanking.fuse([[], []]).isEmpty)58        #expect(MemoryRanking.fuse([[7, 7, 7]]).count == 1)59        // Deterministic whatever the dictionary order.60        for _ in 0..<20 { #expect(MemoryRanking.fuse([[5, 4, 3], [1, 2, 3]]).map(\.id) == [3, 1, 5, 2, 4]) }61    }6263    @Test func vectorScanIsExactAndRespectsFilters() {64        var generator = SystemRandomNumberGenerator()65        var matrix = MemoryVectorMatrix(dimension: 16)66        var vectors: [[Float]] = []67        for index in 0..<500 {68            let vector = MemoryVectorMatrix.normalised((0..<16).map { _ in Float.random(in: -1...1, using: &generator) })!69            vectors.append(vector)70            matrix.append(chunkID: Int64(index), documentID: Int64(index / 5), vector: vector)71        }72        let query = MemoryVectorMatrix.normalised((0..<16).map { _ in Float.random(in: -1...1, using: &generator) })!73        func dot(_ a: [Float], _ b: [Float]) -> Float { zip(a, b).reduce(0) { $0 + $1.0 * $1.1 } }74        let expected = vectors.enumerated().map { (Int64($0.offset), dot($0.element, query)) }.sorted { $0.1 > $1.1 }75        let top = matrix.top(10, query: query)76        #expect(top.map(\.chunkID) == expected.prefix(10).map(\.0))77        for (found, reference) in zip(top, expected) { #expect(abs(found.similarity - reference.1) < 1e-4) }78        let allowed: Set<Int64> = [3, 40, 77]79        let filtered = matrix.top(100, query: query, allowedDocuments: allowed)80        #expect(filtered.count == 15 && filtered.allSatisfy { allowed.contains($0.documentID) })81        #expect(matrix.top(100, query: query, minimumSimilarity: 0.5).allSatisfy { $0.similarity >= 0.5 })82        #expect(matrix.top(0, query: query).isEmpty && matrix.top(5, query: [1, 0]).isEmpty)83        #expect(MemoryVectorMatrix.normalised([0, 0, 0]) == nil && MemoryVectorMatrix.normalised([.nan, 1]) == nil && MemoryVectorMatrix.normalised([]) == nil)84        let blob = MemoryVectorMatrix.data(query)85        #expect(blob.count == 64 && MemoryVectorMatrix.vector(from: blob, dimension: 16) == query)86        #expect(MemoryVectorMatrix.vector(from: blob, dimension: 15) == nil)87    }8889    @Test func snippetsCentreOnTheMatchAndReportHighlights() {90        let text = String(repeating: "Filler words come first. ", count: 30) + "The Élan of the café was remarkable. " + String(repeating: "More filler follows here. ", count: 30)91        let snippet = MemorySnippet.make(from: text, queryWords: ["elan", "cafe", "missing"], length: 120)92        #expect(snippet.text.hasPrefix("…") && snippet.text.hasSuffix("…") && snippet.text.count <= 125)93        let units = Array(snippet.text.utf16)94        let marked = snippet.highlights.map { String(decoding: units[$0], as: UTF16.self) }95        #expect(marked == ["Élan", "café"])96        let none = MemorySnippet.make(from: "Short text without the word.", queryWords: ["zebra"])97        #expect(none.text == "Short text without the word." && none.highlights.isEmpty)98        #expect(MemorySnippet.make(from: "art article ART", queryWords: ["art", "article"]).highlights == [0..<3, 4..<11, 12..<15])99        #expect(MemorySnippet.make(from: "", queryWords: ["x"]).text.isEmpty)100        #expect(MemorySnippet.make(from: "line one\nline two", queryWords: []).text == "line one line two")101    }102}103104@Suite struct MemorySearchTests {105    func seeded() async throws -> Fixture {106        let fixture = try await Fixture.make()107        let day: TimeInterval = 86_400, base: TimeInterval = 1_800_000_000108        try await fixture.index.index(fixture.page("https://autos.example.org/sedans", title: "Sedan review", text: "This sedan is a comfortable vehicle with a quiet cabin and good mileage.",109                                                   space: fixture.space.id, date: Date(timeIntervalSince1970: base)))110        try await fixture.index.index(fixture.page("https://food.example.org/bread", title: "Bread", text: "A recipe to bake sourdough bread in a home kitchen with a cast iron pot.",111                                                   space: fixture.otherSpace.id, date: Date(timeIntervalSince1970: base + day)))112        try await fixture.index.index(fixture.page("https://nature.test/whales", title: "Whales", text: "Whale migration follows the tide across the ocean every spring season.",113                                                   space: fixture.space.id, date: Date(timeIntervalSince1970: base + 2 * day)))114        try await fixture.index.index(MemoryInput(kind: .note, itemID: "note-1", spaceID: fixture.space.id, title: "Garage", text: "Remember to wash the car on Saturday.",115                                                  date: Date(timeIntervalSince1970: base + 3 * day)))116        try await fixture.index.index(MemoryInput(kind: .snapshot, itemID: "snap-1", profileID: fixture.profile.id, url: URL(string: "https://food.example.org/soup"), title: "Soup",117                                                  text: "Cooking a tomato soup takes twenty minutes.", date: Date(timeIntervalSince1970: base + 4 * day)))118        return fixture119    }120121    @Test func hybridSearchFusesFullTextAndSemanticHits() async throws {122        let fixture = try await seeded()123        // "automobile" appears nowhere: only the vectors can find the car texts.124        let semantic = try await fixture.index.search("automobile")125        #expect(semantic.semantic == .used(models: ["stub.en.r1"]) && !semantic.isFullTextOnly)126        #expect(Set(semantic.hits.prefix(2).map(\.itemID)) == ["note-1", "\(fixture.profile.id.string)|https://autos.example.org/sedans"])127        #expect(semantic.hits.prefix(2).allSatisfy { $0.fullTextRank == nil && $0.semanticRank != nil && ($0.similarity ?? 0) > 0.5 })128        #expect(semantic.hits.first?.snippet.highlights.isEmpty == true)129        // A word present in the text is found by both rankers and comes first.130        let both = try await fixture.index.search("sourdough recipe")131        let top = try #require(both.hits.first)132        #expect(top.title == "Bread" && top.fullTextRank == 1 && top.semanticRank != nil && top.kind == .page)133        #expect(top.url?.absoluteString == "https://food.example.org/bread" && top.spaceID == fixture.otherSpace.id && top.profileID == fixture.profile.id)134        let units = Array(top.snippet.text.utf16)135        #expect(Set(top.snippet.highlights.map { String(decoding: units[$0], as: UTF16.self) }) == ["recipe", "sourdough"])136        #expect(both.hits.map(\.score) == both.hits.map(\.score).sorted(by: >))137        // The title is searchable, accents and case are folded, the last word need not be complete… it must be a whole word here.138        #expect(try await fixture.index.search("WHALES").hits.first?.title == "Whales")139        #expect(try await fixture.index.search("zzzunknownzzz").hits.isEmpty)140        #expect(try await fixture.index.search("").hits.isEmpty)141        #expect(try await fixture.index.search("tide", limit: 1).hits.count == 1)142        await fixture.database.close()143    }144145    @Test func filtersRestrictBothRankers() async throws {146        let fixture = try await seeded()147        func ids(_ query: String, _ filter: MemoryFilter) async throws -> Set<String> { Set(try await fixture.index.search(query, filter: filter).hits.map(\.title)) }148        #expect(try await ids("car vehicle cooking", MemoryFilter()) == ["Sedan review", "Garage", "Soup", "Bread"])149        #expect(try await ids("car vehicle cooking", MemoryFilter(kinds: [.note])) == ["Garage"])150        #expect(try await ids("car vehicle cooking", MemoryFilter(kinds: [.page, .snapshot])) == ["Sedan review", "Soup", "Bread"])151        #expect(try await ids("car vehicle cooking", MemoryFilter(kinds: [])) == [])152        #expect(try await ids("car vehicle cooking", MemoryFilter(spaceID: fixture.space.id)) == ["Sedan review", "Garage"])153        #expect(try await ids("car vehicle cooking", MemoryFilter(host: "example.org")) == ["Sedan review", "Soup", "Bread"])154        #expect(try await ids("car vehicle cooking", MemoryFilter(host: "food.example.org")) == ["Soup", "Bread"])155        #expect(try await ids("car vehicle cooking", MemoryFilter(host: "ample.org")) == [])156        #expect(try await ids("car vehicle cooking", MemoryFilter(host: "%")) == [])157        #expect(try await ids("car vehicle cooking", MemoryFilter(profileID: fixture.profile.id)) == ["Sedan review", "Soup", "Bread"])158        #expect(try await ids("car vehicle cooking", MemoryFilter(profileID: ProfileID())) == [])159        let base = Date(timeIntervalSince1970: 1_800_000_000)160        #expect(try await ids("car vehicle cooking", MemoryFilter(dateRange: DateInterval(start: base, duration: 86_400))) == ["Sedan review"])161        #expect(try await ids("car vehicle cooking", MemoryFilter(dateRange: DateInterval(start: base.addingTimeInterval(86_400), duration: 4 * 86_400))) == ["Garage", "Soup", "Bread"])162        #expect(try await ids("car vehicle cooking", MemoryFilter(kinds: [.page], spaceID: fixture.otherSpace.id, host: "example.org")) == ["Bread"])163        // The semantic ranker alone honours the filter too.164        #expect(try await ids("automobile", MemoryFilter(kinds: [.note])) == ["Garage"])165        await fixture.database.close()166    }167168    @Test func arbitraryUserInputIsSafeForFullTextSearch() async throws {169        let fixture = try await seeded()170        let hostile = ["\"", "\"\"\"", "car\"", "NEAR(car vehicle)", "car AND", "OR", "NOT car", "car*", "*", "^car", "title:car", "body : car", "(car", "car)", "{car}",171                       "car -vehicle", "car + vehicle", "'; DROP TABLE memory_documents; --", "\\", "%", "_", "car OR 1=1", String(repeating: "\"car\" ", count: 500),172                       String(repeating: "a", count: 100_000), "\u{0}car\u{0}", "🚗 car 🚗", "c\u{0301}ar", "車", "NEAR", "AND OR NOT", "- - -", "col:\"x\"", "x:y:z", "{a b}: c", "\n\t\r"]173        for query in hostile {174            let response = try await fixture.index.search(query)175            #expect(response.isEnabled, "\(query.prefix(30))")176        }177        // Operators are plain words: "NOT car" finds the car texts instead of excluding them.178        #expect(try await fixture.index.search("NOT car").hits.contains { $0.title == "Garage" })179        #expect(try await fixture.count("memory_documents") == 5)180        await fixture.database.close()181    }182183    @Test func aLanguageWithoutAnEmbeddingIsFullTextOnlyAndSaysSo() async throws {184        let embedder = StubEmbedder(languages: ["en"])185        let fixture = try await Fixture.make(embedder: embedder)186        let french = "La voiture rouge roule lentement sur la petite route de campagne pendant que la pluie tombe sur les champs."187        let outcome = try await fixture.index.index(fixture.page("https://exemple.fr/voiture", title: "Voiture", text: french))188        let report = try #require(outcome.report)189        #expect(report.language == "fr" && report.embeddingModel == nil && report.embeddedChunks == 0 && report.chunks == 1)190        #expect(fixture.index.embeddingModel(for: "fr") == nil && fixture.index.embeddingModel(for: "en")?.dimension == 48)191        // Nothing has a vector: the response states that no semantic search happened.192        let lexical = try await fixture.index.search("voiture")193        #expect(lexical.semantic == .noEmbeddingsInIndex && lexical.isFullTextOnly)194        #expect(lexical.hits.count == 1 && lexical.hits[0].semanticRank == nil && lexical.hits[0].similarity == nil && lexical.hits[0].fullTextRank == 1)195        // A related word that is not in the text finds nothing: no fake semantic match.196        #expect(try await fixture.index.search("auto").hits.isEmpty)197        #expect(try await fixture.count("memory_chunks") == 1)198        #expect(try await fixture.database.sqlite.read { try $0.scalar("SELECT count(*) FROM memory_chunks WHERE embedding IS NOT NULL OR model IS NOT NULL", as: Int.self) } == 0)199200        // With an English document next to it, vectors are used for English only; the French text stays lexical.201        try await fixture.index.index(fixture.page("https://example.org/car", title: "Car", text: "My car is an old sedan that still runs well after many years on the road."))202        let mixed = try await fixture.index.search("automobile")203        #expect(mixed.semantic == .used(models: ["stub.en.r1"]))204        #expect(mixed.hits.map(\.title) == ["Car"])205206        // The model for French arrives (an OS update): the same text is embedded on the next indexing…207        embedder.setLanguages(["en", "fr"])208        #expect(try await fixture.index.index(fixture.page("https://exemple.fr/voiture", title: "Voiture", text: french)).report?.embeddingModel == "stub.fr.r1")209        #expect(try await fixture.index.search("auto").hits.map(\.title).contains("Voiture"))210        // …and disappears again: rebuilding drops the vectors and reports the language.211        embedder.setLanguages(["en"])212        let rebuilt = try await fixture.index.rebuildEmbeddings()213        #expect(rebuilt == MemoryRebuildReport(chunks: 2, embeddedChunks: 1, languagesWithoutModel: ["fr"]))214        #expect(try await fixture.index.search("auto").hits.isEmpty)215        // A model whose identifier changed is never compared with old vectors.216        let renamed = MemoryIndex(database: fixture.database, embedder: StubEmbedder(languages: ["en"], revision: "2"))217        #expect(try await renamed.search("automobile").semantic == .queryNotEmbeddable)218        #expect(try await renamed.rebuildEmbeddings().embeddedChunks == 1)219        #expect(try await renamed.search("automobile").semantic == .used(models: ["stub.en.r2"]))220        await fixture.database.close()221    }222223    @Test func reindexingReplacesAndUnchangedContentIsSkipped() async throws {224        let fixture = try await Fixture.make()225        let long = MemoryChunkingTests.sentences.joined(separator: " ")226        let first = try #require(try await fixture.index.index(fixture.page("https://example.org/a", text: long)).report)227        #expect(first.chunks > 2 && first.embeddedChunks == first.chunks && !first.wasTruncated && first.language == "en")228        #expect(try await fixture.index.index(fixture.page("https://example.org/a", text: long)) == .unchanged)229        #expect(try await fixture.tableCounts() == [1, first.chunks, first.chunks])230        #expect(try await fixture.index.index(fixture.page("https://example.org/a", text: "Now a single short sentence about whales.")).report?.chunks == 1)231        #expect(try await fixture.tableCounts() == [1, 1, 1])232        #expect(try await fixture.index.search("topic").hits.isEmpty)233        #expect(try await fixture.index.search("whales").hits.count == 1)234        // A different title or space is a change.235        #expect(try await fixture.index.index(fixture.page("https://example.org/a", title: "New title", text: "Now a single short sentence about whales.")).report != nil)236        var configuration = MemoryConfiguration()237        configuration.maximumChunksPerDocument = 2238        let capped = MemoryIndex(database: fixture.database, embedder: StubEmbedder(), configuration: configuration)239        let truncated = try #require(try await capped.index(fixture.page("https://example.org/long", text: long)).report)240        #expect(truncated.chunks == 2 && truncated.wasTruncated)241        await fixture.database.close()242    }243}244245@Suite struct MemoryLifecycleTests {246    /// Rows left anywhere for a marker word: documents, chunks, vectors and the full-text index.247    func traces(_ fixture: Fixture, host: String? = nil) async throws -> [Int] {248        let documents = try await fixture.count("memory_documents"), chunks = try await fixture.count("memory_chunks"), fts = try await fixture.count("memory_fts")249        let vectors = try await fixture.database.sqlite.read { try $0.scalar("SELECT count(*) FROM memory_chunks WHERE embedding IS NOT NULL", as: Int.self) ?? 0 }250        let orphans = try await fixture.database.sqlite.read { connection in251            (try connection.scalar("SELECT count(*) FROM memory_chunks WHERE document_id NOT IN (SELECT id FROM memory_documents)", as: Int.self) ?? 0)252                + (try connection.scalar("SELECT count(*) FROM memory_fts WHERE rowid NOT IN (SELECT id FROM memory_chunks)", as: Int.self) ?? 0)253        }254        #expect(orphans == 0)255        return [documents, chunks, vectors, fts]256    }257258    @Test func everyDeletionPathRemovesRowsVectorsAndFullTextEntries() async throws {259        let fixture = try await Fixture.make()260        let long = MemoryChunkingTests.sentences.joined(separator: " ")261        let base = Date(timeIntervalSince1970: 1_800_000_000)262        func seed() async throws {263            try await fixture.index.index(fixture.page("https://a.example.org/1", title: "one", text: long + " zebraone", space: fixture.space.id, date: base))264            try await fixture.index.index(fixture.page("https://b.example.org/2", title: "two", text: long + " zebratwo", space: fixture.otherSpace.id, date: base.addingTimeInterval(100)))265            try await fixture.index.index(fixture.page("https://other.test/3", title: "three", text: long + " zebrathree", date: base.addingTimeInterval(200)))266            try await fixture.index.index(MemoryInput(kind: .note, itemID: "n1", spaceID: fixture.space.id, title: "note", text: "A note about zebranote.", date: base.addingTimeInterval(300)))267        }268        func found(_ word: String) async throws -> Bool { try await !fixture.index.search(word).hits.isEmpty }269        func found(_ words: [String]) async throws -> [Bool] {270            var result: [Bool] = []271            for word in words { result.append(try await found(word)) }272            return result273        }274        try await seed()275        let full = try await traces(fixture)276        #expect(full[0] == 4 && full[1] == full[2] && full[1] == full[3] && full[1] > 8)277        // Warm the vector cache so a stale copy would be noticed.278        #expect(try await found(["zebraone", "zebratwo", "zebrathree", "zebranote"]) == [true, true, true, true])279280        #expect(try await fixture.index.delete(kind: .note, itemID: "n1") == 1)281        #expect(try await found(["zebranote", "zebraone"]) == [false, true])282        #expect(try await fixture.index.delete(kind: .note, itemID: "n1") == 0)283        #expect(try await fixture.index.delete(url: URL(string: "https://other.test/3")!) == 1)284        #expect(try await !found("zebrathree"))285        #expect(try await fixture.index.delete(host: "example.org", includingSubdomains: false) == 0)286        #expect(try await fixture.index.delete(host: "a.example.org", includingSubdomains: false) == 1)287        #expect(try await fixture.index.delete(host: "EXAMPLE.org") == 1)288        #expect(try await traces(fixture) == [0, 0, 0, 0])289        #expect(try await fixture.index.search("sentence topic detail").hits.isEmpty)290291        try await seed()292        #expect(try await fixture.index.delete(in: DateInterval(start: base.addingTimeInterval(100), duration: 100)) == 1)   // half-open: only "two"293        #expect(try await found(["zebratwo", "zebrathree"]) == [false, true])294        #expect(try await fixture.index.delete(space: fixture.space.id) == 2)295        #expect(try await found(["zebraone", "zebranote", "zebrathree"]) == [false, false, true])296        #expect(try await fixture.index.delete(profile: fixture.profile.id) == 1)297        #expect(try await traces(fixture) == [0, 0, 0, 0])298299        try await seed()300        try await fixture.index.deleteEverything()301        #expect(try await traces(fixture) == [0, 0, 0, 0])302        #expect(try await fixture.index.search("zebraone sentence").hits.isEmpty)303        // Not one term survives in the FTS5 structures, and no vector blob in the file image of the tables.304        let segments = try await fixture.database.sqlite.read { try $0.scalar("SELECT count(*) FROM memory_fts_data WHERE id > 10", as: Int.self) ?? 0 }305        #expect(segments == 0)306        #expect(try await fixture.index.statistics().bytes == 0)307        // The opt-in and the settings survive; the index works again afterwards.308        #expect(try await fixture.index.isEnabled())309        try await seed()310        #expect(try await found("zebraone"))311        await fixture.database.close()312    }313314    @Test func storageIsAccountedAndCappedOldestFirst() async throws {315        let fixture = try await Fixture.make()316        let text = String(repeating: "Storage accounting sentence with several words. ", count: 12)317        for index in 0..<6 {318            try await fixture.index.index(fixture.page("https://example.org/\(index)", title: "p\(index)", text: text + "marker\(index)"))319            try await Task.sleep(for: .milliseconds(3))320        }321        let before = try await fixture.index.statistics()322        #expect(before.documents == 6 && before.chunks == before.embeddedChunks && before.documentsByKind == [.page: 6])323        #expect(before.embeddingModels == ["stub.en.r1": before.chunks] && before.capBytes == 256 * 1024 * 1024)324        let perDocument = before.bytes / 6325        #expect(perDocument > Int64(text.utf8.count) && perDocument < Int64(text.utf8.count) + 2_000)326        // Room for three documents and a half: the three oldest go.327        #expect(try await fixture.index.setStorageCap(bytes: perDocument * 3 + perDocument / 2) == 3)328        let after = try await fixture.index.statistics()329        #expect(after.documents == 3 && after.bytes <= after.capBytes)330        func hitCounts(_ words: [String]) async throws -> [Int] {331            var result: [Int] = []332            for word in words { result.append(try await fixture.index.search(word).hits.count) }333            return result334        }335        #expect(try await hitCounts(["marker0", "marker2", "marker3", "marker5"]) == [0, 0, 1, 1])336        // Indexing one more evicts the oldest remaining one.337        let report = try #require(try await fixture.index.index(fixture.page("https://example.org/new", title: "new", text: text + "markernew")).report)338        #expect(report.evictedDocuments == 1)339        #expect(try await hitCounts(["marker3", "markernew"]) == [0, 1])340        // Something bigger than the whole cap is refused rather than emptying the index.341        let huge = String(repeating: text, count: 20)342        #expect(try await fixture.index.index(fixture.page("https://example.org/huge", text: huge)) == .skipped(.tooLarge))343        #expect(try await fixture.index.statistics().documents == 3)344        #expect(try await fixture.index.setStorageCap(bytes: 0) == 3)345        #expect(try await fixture.tableCounts() == [0, 0, 0])346        await fixture.database.close()347    }348349    @Test func theIndexStaysOutOfExportsAndTheDatabaseKeepsWorking() async throws {350        let fixture = try await Fixture.make()351        try await fixture.index.index(fixture.page("https://example.org/a", title: "MARKERTITLE", text: "A sentence holding MARKERBODY for the export test."))352        let export = try await fixture.database.lifecycle.exportJSON()353        let text = String(decoding: export, as: UTF8.self)354        #expect(!text.contains("MARKERBODY") && !text.contains("MARKERTITLE"))355        #expect(try await fixture.database.checkIntegrity(full: true).isEmpty)356        // A second index object on the same database shares the tables.357        let second = MemoryIndex(database: fixture.database, embedder: StubEmbedder())358        #expect(try await second.search("MARKERBODY").hits.count == 1)359        await fixture.index.releaseVectorCache()360        #expect(try await fixture.index.search("MARKERBODY").hits.first?.semanticRank != nil)361        await fixture.database.close()362    }363364    @Test func inputHelpersBuildTheRightItems() {365        let profile = ProfileID(), space = SpaceID()366        let note = Note(spaceID: space, url: URL(string: "https://example.org/n"), title: "T", body: "Body", quote: "Quote")367        let fromNote = MemoryInput.note(note)368        #expect(fromNote.kind == .note && fromNote.itemID == note.id.string && fromNote.text == "Quote\n\nBody" && fromNote.spaceID == space && fromNote.profileID == nil)369        let snapshot = PageSnapshot(profileID: profile, url: URL(string: "https://example.org/s")!, title: "S", text: "Snap")370        #expect(MemoryInput.snapshot(snapshot).itemID == snapshot.id.string && MemoryInput.snapshot(snapshot).profileID == profile)371        let archive = Archive(profileID: profile, url: URL(string: "https://example.org/a")!, title: "A", format: .html, relativePath: "a.html", byteSize: 1, contentHash: "h", isComplete: true)372        #expect(MemoryInput.archive(archive, text: "x").kind == .archive)373        let page = MemoryInput.page(url: URL(string: "https://example.org/p")!, title: "P", text: "x", profileID: profile, facts: MemoryPageFacts())374        #expect(page.itemID == "\(profile.string)|https://example.org/p")375    }376}377378@Suite(.serialized) struct MemoryMeasurementTests {379    @Test func appleSentenceEmbeddingAvailabilityOnThisMachine() async throws {380        let embedder = NLSentenceMemoryEmbedder()381        var available: [String] = []382        for language in ["en", "fr", "de", "es", "it", "pt", "nl", "ja", "zh-Hans", "ru", "ar", "und", "xx"] {383            if let model = embedder.model(for: language) {384                available.append("\(language): \(model.identifier) dim \(model.dimension)")385                let vectors = embedder.embed(["A short sentence."], language: language)386                #expect(vectors.first??.count == model.dimension)387            } else {388                #expect(embedder.embed(["A short sentence."], language: language) == [nil])389            }390        }391        print("[memory] NLEmbedding.sentenceEmbedding available here: \(available.isEmpty ? "none" : available.joined(separator: "; "))")392        let contextual = NLContextualMemoryEmbedder()393        print("[memory] NLContextualEmbedding assets already on this machine: en=\(contextual.hasAssets(for: "en")) fr=\(contextual.hasAssets(for: "fr"))")394        #expect(embedder.model(for: "xx") == nil)395        #expect(MemoryLanguage.detect("Ceci est une phrase écrite en français, sans aucun doute possible.") == "fr")396        #expect(MemoryLanguage.detect("This is a sentence written in English, beyond any doubt.") == "en")397        #expect(NoMemoryEmbedder().model(for: "en") == nil)398399        // End to end with the real model when the machine has it; otherwise the index must say it is lexical.400        let fixture = try await Fixture.make(embedder: PreferredMemoryEmbedder([NLSentenceMemoryEmbedder()]))401        let car = try await fixture.index.index(fixture.page("https://example.org/car", title: "Car", text: "The mechanic repaired the engine of my car and changed the tires before the long road trip."))402        try await fixture.index.index(fixture.page("https://example.org/soup", title: "Soup", text: "Simmer the tomatoes with garlic and basil, then blend the soup until it is smooth."))403        let response = try await fixture.index.search("fixing an automobile")404        if embedder.model(for: "en") != nil {405            #expect(car.report?.embeddingModel?.hasPrefix("apple.nl.sentence.en") == true)406            guard case .used = response.semantic else { Issue.record("expected semantic search with the system model"); return }407            let ranked = response.hits.map { "\($0.title) \(String(format: "%.3f", $0.similarity ?? 0))" }408            print("[memory] real model, query “fixing an automobile” (no word in common with either text): \(ranked)")409            if car.report?.embeddingModel == "apple.nl.sentence.en.r1" { #expect(response.hits.first?.title == "Car") }410        } else {411            #expect(car.report?.embeddingModel == nil && response.semantic == .noEmbeddingsInIndex)412            print("[memory] no English sentence embedding on this machine: index is full-text only")413        }414        await fixture.database.close()415    }416417    @Test(arguments: [10_000, 50_000])418    func benchmarkExactVectorScan(count: Int) async throws {419        let dimension = 512420        var generator = SystemRandomNumberGenerator()421        func randomVector() -> [Float] { MemoryVectorMatrix.normalised((0..<dimension).map { _ in Float.random(in: -1...1, using: &generator) })! }422        // Rows go through SQLite exactly as real vectors do, so the cold number includes reading the blobs.423        let database = try await NavigatorDatabase.inMemory()424        let index = MemoryIndex(database: database, embedder: NoMemoryEmbedder())425        try await index.prepare()426        let base = randomVector()427        let blobs: [Data] = (0..<count).map { row in428            var vector = base429            // Cheap variation per row; exact values do not matter for timing.430            vector[row % dimension] += 0.5; vector[(row * 7) % dimension] -= 0.25431            return MemoryVectorMatrix.data(MemoryVectorMatrix.normalised(vector)!)432        }433        try await database.sqlite.transaction { connection in434            for document in 0..<(count / 10) {435                try connection.execute("""436                INSERT INTO memory_documents (id, kind, item_id, title, language, content_hash, source_date, indexed_at, byte_size, chunk_count)437                VALUES (?, 'page', ?, 't', 'en', 'h', 0, 0, 0, 10)438                """, [document + 1, "doc-\(document)"])439            }440            for row in 0..<count {441                try connection.execute("INSERT INTO memory_chunks (id, document_id, ordinal, model, dimension, embedding) VALUES (?, ?, ?, 'bench', ?, ?)",442                                       [row + 1, row / 10 + 1, row % 10, dimension, blobs[row]])443            }444        }445        let clock = ContinuousClock()446        func milliseconds(_ duration: Duration) -> Double { Double(duration.components.seconds) * 1_000 + Double(duration.components.attoseconds) / 1e15 }447        var matrix = MemoryVectorMatrix(dimension: dimension)448        let load = try await clock.measure {449            matrix = try await database.sqlite.read { connection in450                var loaded = MemoryVectorMatrix(dimension: dimension, capacity: count)451                for row in try connection.query("SELECT id, document_id, embedding FROM memory_chunks WHERE model = 'bench' ORDER BY id") {452                    loaded.append(chunkID: try row.get("id"), documentID: try row.get("document_id"),453                                  vector: MemoryVectorMatrix.vector(from: try row.get("embedding", as: Data.self), dimension: dimension)!)454                }455                return loaded456            }457        }458        #expect(matrix.count == count)459        let query = randomVector()460        var found = 0461        let runs = 30462        let scan = clock.measure { for _ in 0..<runs { found = matrix.top(100, query: query).count } }463        let allowed = Set((0..<(count / 100)).map { Int64($0 * 10 + 1) })464        let filtered = clock.measure { for _ in 0..<runs { _ = matrix.top(100, query: query, allowedDocuments: allowed) } }465        #expect(found == 100)466        print("[benchmark] memory vector scan, \(count) chunks × \(dimension) dims (\(matrix.byteSize / 1_048_576) MiB): "467              + "exact top-100 \(String(format: "%.2f", milliseconds(scan) / Double(runs))) ms, "468              + "with a 10 % document filter \(String(format: "%.2f", milliseconds(filtered) / Double(runs))) ms, "469              + "cold load from SQLite \(String(format: "%.0f", milliseconds(load))) ms")470        await database.close()471    }472}473
Files main
Menu

Theme