SPB Git

Repository Public License

MemoryTestSupport.swift 4.1 KB 88 lines swift

1import Foundation2import NavigatorCore3import Persistence4import Synchronization5import Testing6@testable import MemoryEngine78/// A deterministic stand-in for an embedding model: each word adds weight to one of 48 dimensions, and a few9/// groups of related words share a dimension, so "automobile" is close to "car" without sharing a letter.10final class StubEmbedder: MemoryEmbedder, Sendable {11    static let dimension = 4812    static let concepts: [[String]] = [["car", "cars", "automobile", "vehicle", "sedan"], ["cook", "cooking", "recipe", "kitchen", "bake"],13                                       ["ocean", "sea", "marine", "whale", "tide"], ["voiture", "auto"]]14    let languages: Mutex<Set<String>>15    let revision: String1617    init(languages: Set<String> = ["en"], revision: String = "1") { self.languages = Mutex(languages); self.revision = revision }1819    func setLanguages(_ value: Set<String>) { languages.withLock { $0 = value } }2021    func model(for language: String) -> MemoryEmbeddingModel? {22        languages.withLock { $0.contains(language) } ? MemoryEmbeddingModel(identifier: "stub.\(language).r\(revision)", dimension: Self.dimension, language: language) : nil23    }2425    static func vector(_ text: String) -> [Float]? {26        var vector = [Float](repeating: 0, count: dimension)27        var any = false28        for word in text.lowercased().split(whereSeparator: { !$0.isLetter }) {29            let word = String(word)30            if let concept = concepts.firstIndex(where: { $0.contains(word) }) {31                vector[concept] += 332            } else {33                var hash: UInt64 = 1_469_598_103_934_665_60334                for byte in word.utf8 { hash = (hash ^ UInt64(byte)) &* 1_099_511_628_211 }35                vector[concepts.count + Int(hash % UInt64(dimension - concepts.count))] += 0.2536            }37            any = true38        }39        return any ? vector : nil40    }4142    func embed(_ texts: [String], language: String) -> [[Float]?] {43        guard model(for: language) != nil else { return texts.map { _ in nil } }44        return texts.map(Self.vector)45    }46}4748struct Fixture {49    let database: NavigatorDatabase50    let index: MemoryIndex51    let profile: Profile52    let space: OrbitSpace53    let otherSpace: OrbitSpace5455    static func make(enabled: Bool = true, embedder: any MemoryEmbedder = StubEmbedder(),56                     configuration: MemoryConfiguration = MemoryConfiguration()) async throws -> Fixture {57        let database = try await NavigatorDatabase.inMemory()58        let profile = Profile(name: "Personal")59        try await database.profiles.save(profile)60        let space = OrbitSpace(profileID: profile.id, name: "Research"), other = OrbitSpace(profileID: profile.id, name: "Home", order: 1)61        try await database.spaces.save(space)62        try await database.spaces.save(other)63        let index = MemoryIndex(database: database, embedder: embedder, configuration: configuration)64        if enabled { try await index.setEnabled(true, purge: false) }65        return Fixture(database: database, index: index, profile: profile, space: space, otherSpace: other)66    }6768    func page(_ address: String, title: String = "Page", text: String, space: SpaceID? = nil, date: Date = Date(timeIntervalSince1970: 1_800_000_000),69              facts: MemoryPageFacts = MemoryPageFacts()) -> MemoryInput {70        MemoryInput.page(url: URL(string: address)!, title: title, text: text, profileID: profile.id, spaceID: space, date: date, facts: facts)71    }7273    func count(_ table: String) async throws -> Int {74        try await database.sqlite.read { try $0.scalar("SELECT count(*) FROM \(table)", as: Int.self) ?? 0 }75    }7677    func tableCounts() async throws -> [Int] {78        [try await count("memory_documents"), try await count("memory_chunks"), try await count("memory_fts")]79    }80}8182extension MemoryIndexOutcome {83    var report: MemoryIndexReport? { if case .indexed(let report) = self { return report } else { return nil } }84    var skipReason: MemorySkipReason? { if case .skipped(let reason) = self { return reason } else { return nil } }85}8687let english = "The quick brown fox jumps over the lazy dog near the river bank in the morning light."88
Files main
Menu

Theme