Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Tests/AstraPersistenceTests/SchemaTests.swift10// Module : AstraPersistenceTests11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import Testing90import CryptoKit91import GRDB92import AstraCore93@testable import AstraPersistence9495@Suite struct SchemaTests {96 /// SHA-256 of the schema each migration prefix produces. Editing a shipped migration changes its hash and fails here:97 /// add a new `vN_…` migration and append its hash instead.98 static let pinned: [String] = [99 "5c59e00305b5180711bbad7948c6b2f37bae75eab62da9be09cbce839cf35315",100 ]101102 static func schemaHash(_ db: Database) throws -> String {103 // FTS5 shadow tables are created by SQLite itself and may differ between SQLite versions: only our own statements count.104 let rows = try Row.fetchAll(db, sql: """105 SELECT type, name, tbl_name, sql FROM sqlite_master106 WHERE name NOT LIKE 'sqlite_%' AND name NOT LIKE '%\\_fts\\_%' ESCAPE '\\' AND name <> 'grdb_migrations' ORDER BY type, name107 """)108 let text = rows.map { row in [row[0] as String, row[1] as String, row[2] as String, (row[3] as String?) ?? ""].joined(separator: "\u{1F}") }109 .joined(separator: "\u{1E}")110 return SHA256.hash(data: Data(text.utf8)).map { String(format: "%02x", $0) }.joined()111 }112113 @Test func migrationsAreNamedAndVersioned() async throws {114 #expect(AstraSchema.currentVersion == AstraSchema.migrationNames.count)115 for (index, name) in AstraSchema.migrationNames.enumerated() { #expect(name.hasPrefix("v\(index + 1)_")) }116 let store = try makeStore()117 #expect(try await store.schemaVersion() == AstraSchema.currentVersion)118 #expect(try await store.appliedMigrations() == AstraSchema.migrationNames)119 }120121 @Test func schemaIsStable() throws {122 #expect(Self.pinned.count == AstraSchema.currentVersion, "Every migration needs a pinned schema hash.")123 for version in 1...AstraSchema.currentVersion {124 let queue = try DatabaseQueue()125 try AstraSchema.migrator(through: version).migrate(queue)126 let hash = try queue.read(Self.schemaHash)127 if version > Self.pinned.count || Self.pinned[version - 1] != hash { print("schema hash v\(version): \(hash)") }128 #expect(version <= Self.pinned.count && Self.pinned[version - 1] == hash,129 "Schema after migration \(version) changed. Never edit a shipped migration: add a new one.")130 }131 }132133 @Test func version1DatabaseUpgradesAndKeepsItsData() async throws {134 let directory = try temporaryDirectory()135 defer { try? FileManager.default.removeItem(at: directory) }136 let url = directory.appendingPathComponent("astra.sqlite")137 do {138 // A database as version 1 of the app left it, written with plain SQL so the test does not depend on today's record types.139 let old = try DatabaseQueue(path: url.path)140 try AstraSchema.migrator(through: 1).migrate(old)141 try await old.write { db in142 try db.execute(sql: """143 INSERT INTO conversation(id, title, createdAt, updatedAt, model, parameters, truncationStrategy, activeLeafID)144 VALUES ('c1', 'Old chat about tides', 1, 2, '{"provider":"openAI","modelID":"gpt-old"}', '{"stop":[]}', 'dropOldest', 'm1');145 INSERT INTO message(id, conversationID, role, text, status, createdAt, updatedAt)146 VALUES ('m1', 'c1', 'user', 'Why are there two tides a day?', 'complete', 1, 1);147 INSERT INTO setting(key, value) VALUES ('theme', '"dark"');148 """)149 }150 try old.close()151 }152 let store = try await AstraStore.open(url: url)153 #expect(try await store.schemaVersion() == AstraSchema.currentVersion)154 let conversation = try #require(try await store.conversation(id: "c1"))155 #expect(conversation.title == "Old chat about tides")156 #expect(conversation.model == ModelRef(provider: .openAI, modelID: "gpt-old"))157 #expect(try await store.activePath(conversationID: "c1").map(\.text) == ["Why are there two tides a day?"])158 #expect(try await store.setting("theme", as: String.self) == "dark")159 #expect(try await store.searchConversations("tides").first?.conversation.id == "c1")160 }161162 @Test func fileStoreUsesWALAndForeignKeys() async throws {163 let directory = try temporaryDirectory()164 defer { try? FileManager.default.removeItem(at: directory) }165 let store = try AstraStore(url: directory.appendingPathComponent("db/astra.sqlite"))166 let (mode, keys) = try await store.read { db in167 (try String.fetchOne(db, sql: "PRAGMA journal_mode"), try Int.fetchOne(db, sql: "PRAGMA foreign_keys"))168 }169 #expect(mode == "wal")170 #expect(keys == 1)171 #expect(store.attachmentsDirectory.lastPathComponent == "Attachments")172 #expect(FileManager.default.fileExists(atPath: store.attachmentsDirectory.path))173 await #expect(throws: (any Error).self) {174 try await store.write { db in175 try db.execute(sql: "INSERT INTO message(id, conversationID, role, status, createdAt, updatedAt) VALUES ('x', 'missing', 'user', 'complete', 0, 0)")176 }177 }178 }179180 @Test func datesRoundTripExactly() async throws {181 let store = try makeStore()182 let odd = Date(timeIntervalSinceReferenceDate: 800_000_000.123456789)183 let conversation = try await store.createConversation(model: gpt, at: odd)184 let message = try await store.appendUserMessage(conversationID: conversation.id, text: "x", at: odd)185 #expect(try await store.conversation(id: conversation.id)?.createdAt == odd)186 #expect(try await store.message(id: message.id)?.createdAt == odd)187 let stored = try await store.read { db in try Double.fetchOne(db, sql: "SELECT createdAt FROM conversation") }188 #expect(stored == odd.timeIntervalSinceReferenceDate)189 }190191 @Test func dataSurvivesReopening() async throws {192 let directory = try temporaryDirectory()193 defer { try? FileManager.default.removeItem(at: directory) }194 let url = directory.appendingPathComponent("astra.sqlite")195 var id = ""196 do {197 let store = try AstraStore(url: url)198 let conversation = try await store.createConversation(title: "Kept", model: claude)199 id = conversation.id200 try await store.exchange(id, "question", "answer")201 }202 let reopened = try AstraStore(url: url)203 #expect(try await reopened.conversation(id: id)?.title == "Kept")204 #expect(try await reopened.activePath(conversationID: id).map(\.text) == ["question", "answer"])205 }206}207