SPB Git

Repository Public MIT

MessageTests.swift 31.1 KB 496 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraPersistenceTests/MessageTests.swift10// Module           : AstraPersistenceTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2214//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 AstraCore91@testable import AstraPersistence9293@Suite struct MessageTests {94    @Test func activePathFollowsAppends() async throws {95        let store = try makeStore()96        let conversation = try await store.createConversation(model: gpt, at: t(0))97        #expect(try await store.activePath(conversationID: conversation.id).isEmpty)98        let one = try await store.exchange(conversation.id, "q1", "a1", at: 1)99        let two = try await store.exchange(conversation.id, "q2", "a2", at: 3)100        let path = try await store.activePath(conversationID: conversation.id)101        #expect(path.map(\.text) == ["q1", "a1", "q2", "a2"])102        #expect(path.map(\.role) == [.user, .assistant, .user, .assistant])103        #expect(path[1].parentID == one.user.id)104        #expect(path[2].parentID == one.assistant.id)105        #expect(try await store.conversation(id: conversation.id)?.activeLeafID == two.assistant.id)106        #expect(try await store.conversation(id: conversation.id)?.updatedAt == t(4))107        #expect(try await store.activePath(conversationID: conversation.id, last: 2).map(\.text) == ["q2", "a2"])108        #expect(try await store.path(toMessage: one.assistant.id).map(\.text) == ["q1", "a1"])109        #expect(try await store.messageCount(conversationID: conversation.id) == 4)110        #expect(try await store.activePath(conversationID: "missing").isEmpty)111        await #expect(throws: AstraStoreError.self) { try await store.appendUserMessage(conversationID: "missing", text: "x") }112    }113114    @Test func assistantMessageKeepsEverythingReported() async throws {115        let store = try makeStore()116        let conversation = try await store.createConversation(model: gpt)117        try await store.appendUserMessage(conversationID: conversation.id, text: "call a tool")118        let draft = try await store.beginAssistantMessage(conversationID: conversation.id, model: ModelRef(provider: .openRouter, modelID: "vendor/model"))119        #expect(draft.status == .streaming)120        let call = ToolCall(id: "call_1", name: "search", arguments: ["q": "tides", "n": 3])121        let completion = MessageCompletion(text: "Looking it up.", reasoningSummary: "Need data.", toolCalls: [call], reportedModel: "vendor/model-2026",122                                           servedBy: "UpstreamCo", usage: TokenUsage(inputTokens: 100, outputTokens: 50, cachedInputTokens: 40, reasoningTokens: 8, reportedCostUSD: 0.0012),123                                           stopReason: .toolCalls, cost: CostEstimate(amountUSD: 0.0012, basis: .reportedByProvider), timeToFirstToken: 0.4, totalTime: 2.4)124        try await store.finalizeAssistantMessage(id: draft.id, completion)125        let saved = try #require(try await store.message(id: draft.id))126        #expect(saved.status == .complete)127        #expect(saved.toolCalls == [call])128        #expect(saved.reasoningSummary == "Need data.")129        #expect(saved.model == ModelRef(provider: .openRouter, modelID: "vendor/model"))130        #expect(saved.reportedModel == "vendor/model-2026")131        #expect(saved.servedBy == "UpstreamCo")132        #expect(saved.usage == completion.usage)133        #expect(saved.stopReason == .toolCalls)134        #expect(saved.cost == completion.cost)135        #expect(saved.timeToFirstToken == 0.4)136        #expect(saved.totalTime == 2.4)137        // visible tokens (output minus hidden reasoning) over the 2.0 s streaming phase138        #expect(saved.tokensPerSecond == Double((completion.usage?.outputTokens ?? 0) - (completion.usage?.reasoningTokens ?? 0)) / 2.0)139        let tool = try await store.appendToolMessage(conversationID: conversation.id, text: "{\"hits\":2}", toolCallID: "call_1", toolName: "search")140        #expect(tool.parentID == draft.id)141        let prompt = try await store.activePath(conversationID: conversation.id).map(\.promptMessage)142        #expect(prompt.map(\.role) == [.user, .assistant, .tool])143        #expect(prompt[1].toolCalls == [call])144        #expect(prompt[2].toolCallID == "call_1")145        #expect(prompt[2].toolName == "search")146        // The ledger got exactly one row, for the generation.147        let usage = try await store.usageRecords()148        #expect(usage.count == 1)149        #expect(usage.first?.origin == .conversation)150        #expect(usage.first?.originID == conversation.id)151        #expect(usage.first?.costUSD == 0.0012)152        #expect(usage.first?.cachedInputTokens == 40)153        await #expect(throws: AstraStoreError.self) { try await store.finalizeAssistantMessage(id: tool.id, MessageCompletion(text: "x")) }154    }155156    @Test func failedGenerationKeepsItsTypedError() async throws {157        let store = try makeStore()158        let conversation = try await store.createConversation(model: gpt)159        try await store.appendUserMessage(conversationID: conversation.id, text: "hi")160        let draft = try await store.beginAssistantMessage(conversationID: conversation.id, model: gpt)161        var outcome = GenerationOutcome()162        outcome.apply(.textDelta("partial"))163        outcome.apply(.error(.rateLimited(retryAfter: 12, message: "slow down")))164        try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(outcome: outcome))165        let saved = try #require(try await store.message(id: draft.id))166        #expect(saved.status == .failed)167        #expect(saved.error == .rateLimited(retryAfter: 12, message: "slow down"))168        #expect(saved.text == "partial")169        #expect(saved.stopReason == .error)170        var cancelled = GenerationOutcome()171        cancelled.apply(.error(.cancelled))172        #expect(MessageCompletion(outcome: cancelled).status == .stopped)173        #expect(MessageCompletion(outcome: GenerationOutcome()).status == .complete)174    }175176    @Test func editAndResendCreatesASiblingBranch() async throws {177        let store = try makeStore()178        let conversation = try await store.createConversation(model: gpt, at: t(0))179        let first = try await store.exchange(conversation.id, "q1", "a1", at: 1)180        let second = try await store.exchange(conversation.id, "q2 original", "a2 original", at: 3)181        let edited = try await store.editAndResend(messageID: second.user.id, newText: "q2 edited", at: t(10))182        #expect(edited.parentID == first.assistant.id)183        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q1", "a1", "q2 edited"])184        let draft = try await store.beginAssistantMessage(conversationID: conversation.id, model: gpt, at: t(11))185        try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(text: "a2 edited"), at: t(12))186        #expect(try await store.siblings(of: edited.id).map(\.text) == ["q2 original", "q2 edited"])187        #expect(try await store.siblings(of: second.user.id).map(\.id) == [second.user.id, edited.id])188        // Nothing of the original branch is lost.189        #expect(try await store.path(toMessage: second.assistant.id).map(\.text) == ["q1", "a1", "q2 original", "a2 original"])190        #expect(try await store.messageCount(conversationID: conversation.id) == 6)191        // Going back to the original branch selects its leaf.192        let leaf = try await store.selectBranch(messageID: second.user.id)193        #expect(leaf == second.assistant.id)194        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q1", "a1", "q2 original", "a2 original"])195        let positions = try await store.branchPositions(conversationID: conversation.id)196        #expect(positions[second.user.id] == BranchPosition(index: 0, count: 2, siblingIDs: [second.user.id, edited.id]))197        #expect(positions[edited.id]?.index == 1)198        #expect(positions[first.user.id] == nil)199        await #expect(throws: AstraStoreError.self) { try await store.editAndResend(messageID: first.assistant.id, newText: "x") }200    }201202    @Test func editingTheFirstMessageCreatesASecondRoot() async throws {203        let store = try makeStore()204        let conversation = try await store.createConversation(model: gpt, at: t(0))205        let original = try await store.exchange(conversation.id, "root one", "answer one", at: 1)206        let image = AttachmentDraft(kind: .image, filename: "p.png", mimeType: "image/png", data: Data([5]))207        try await store.addAttachment(messageID: original.user.id, image)208        let edited = try await store.editAndResend(messageID: original.user.id, newText: "root two", at: t(5))209        #expect(edited.parentID == nil)210        #expect(try await store.siblings(of: edited.id).map(\.text) == ["root one", "root two"])211        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["root two"])212        // Attachments follow the edit unless asked otherwise.213        #expect(try await store.attachments(messageID: edited.id).map(\.filename) == ["p.png"])214        let bare = try await store.editAndResend(messageID: original.user.id, newText: "root three", keepAttachments: false, at: t(6))215        #expect(try await store.attachments(messageID: bare.id).isEmpty)216        #expect(try await store.branchPositions(conversationID: conversation.id)[bare.id]?.count == 3)217        try await store.selectBranch(messageID: original.user.id)218        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["root one", "answer one"])219    }220221    @Test func regenerateCreatesAnAssistantSibling() async throws {222        let store = try makeStore()223        let conversation = try await store.createConversation(model: gpt, at: t(0))224        let pair = try await store.exchange(conversation.id, "q", "first answer", at: 1)225        let second = try await store.regenerate(assistantMessageID: pair.assistant.id, at: t(5))226        #expect(second.status == .streaming)227        #expect(second.parentID == pair.user.id)228        #expect(second.model == gpt)229        try await store.finalizeAssistantMessage(id: second.id, MessageCompletion(text: "second answer"), at: t(6))230        let third = try await store.regenerate(assistantMessageID: second.id, model: claude, at: t(7))231        #expect(third.model == claude)232        try await store.finalizeAssistantMessage(id: third.id, MessageCompletion(text: "third answer"), at: t(8))233        #expect(try await store.siblings(of: pair.assistant.id).map(\.text) == ["first answer", "second answer", "third answer"])234        #expect(try await store.children(of: pair.user.id).count == 3)235        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q", "third answer"])236        await #expect(throws: AstraStoreError.self) { try await store.regenerate(assistantMessageID: pair.user.id) }237    }238239    @Test func selectBranchPicksTheDeepestMostRecentDescendant() async throws {240        let store = try makeStore()241        let conversation = try await store.createConversation(model: gpt, at: t(0))242        let root = try await store.exchange(conversation.id, "q", "a", at: 1)243        // Under `a`: an old deep branch and a newer shallow one.244        let old = try await store.exchange(conversation.id, "old q", "old a", at: 10)245        try await store.exchange(conversation.id, "old q2", "old a2", at: 12)246        let recent = try await store.appendUserMessage(conversationID: conversation.id, text: "recent q", parentID: root.assistant.id, at: t(20))247        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q", "a", "recent q"])248        // Selecting the fork's parent follows the most recent child at each level.249        #expect(try await store.selectBranch(messageID: root.assistant.id) == recent.id)250        // Selecting inside the old branch goes all the way down it.251        try await store.selectBranch(messageID: old.user.id)252        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q", "a", "old q", "old a", "old q2", "old a2"])253        // Selecting a leaf selects itself.254        #expect(try await store.selectBranch(messageID: recent.id) == recent.id)255        await #expect(throws: AstraStoreError.self) { try await store.selectBranch(messageID: "missing") }256        // A message can only be attached under a message of the same conversation.257        let other = try await store.createConversation(model: gpt)258        await #expect(throws: AstraStoreError.self) { try await store.appendUserMessage(conversationID: other.id, text: "x", parentID: recent.id) }259    }260261    @Test func siblingOrderIsDeterministicWithIdenticalTimestamps() async throws {262        let store = try makeStore()263        let conversation = try await store.createConversation(model: gpt, at: t(0))264        let pair = try await store.exchange(conversation.id, "q", "a", at: 1)265        var created: [String] = [pair.assistant.id]266        // `a` itself was created at t(1.5); give every alternative the very same instant.267        for index in 0..<12 {268            let draft = try await store.regenerate(assistantMessageID: pair.assistant.id, at: t(1.5))269            try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(text: "alt \(index)"), at: t(2))270            created.append(draft.id)271        }272        let expected = created.sorted()273        for _ in 0..<5 { #expect(try await store.siblings(of: pair.assistant.id).map(\.id) == expected) }274        // With equal timestamps "most recent" is the greatest id: selection is stable too.275        for _ in 0..<5 { #expect(try await store.selectBranch(messageID: pair.user.id) == expected.last) }276        let positions = try await store.branchPositions(conversationID: conversation.id)277        #expect(positions[expected[3]] == BranchPosition(index: 3, count: 13, siblingIDs: expected))278    }279280    @Test func streamingTextIsPersistedIncrementallyAndRecoveredAtLaunch() async throws {281        let directory = try temporaryDirectory()282        defer { try? FileManager.default.removeItem(at: directory) }283        let url = directory.appendingPathComponent("astra.sqlite")284        var conversationID = "", draftID = "", finishedID = ""285        do {286            let store = try AstraStore(url: url)287            let conversation = try await store.createConversation(model: gpt)288            conversationID = conversation.id289            finishedID = try await store.exchange(conversationID, "first", "finished answer").assistant.id290            try await store.appendUserMessage(conversationID: conversationID, text: "tell me about lighthouses")291            let draft = try await store.beginAssistantMessage(conversationID: conversationID, model: gpt)292            draftID = draft.id293            var text = ""294            for word in ["Lighthouses", " guide", " ships", " at", " night"] {295                text += word296                try await store.updateStreaming(id: draftID, text: text, reasoning: "thinking")297            }298            // Partial text is on disk but not searchable while streaming.299            #expect(try await store.message(id: draftID)?.text == "Lighthouses guide ships at night")300            #expect(try await store.searchConversations("ships").isEmpty)301            // The process "dies" here: the store is dropped without finalizing.302        }303        let store = try AstraStore(url: url)304        #expect(try await store.message(id: draftID)?.status == .streaming)305        #expect(try await store.recoverInterruptedMessages() == 1)306        let recovered = try #require(try await store.message(id: draftID))307        #expect(recovered.status == .stopped)308        #expect(recovered.stopReason == .cancelled)309        #expect(recovered.text == "Lighthouses guide ships at night")310        #expect(recovered.reasoningSummary == "thinking")311        #expect(try await store.message(id: finishedID)?.status == .complete)312        #expect(try await store.recoverInterruptedMessages() == 0)313        // Recovered text is now indexed, and late streaming updates are ignored.314        #expect(try await store.searchConversations("ships").first?.messageID == draftID)315        try await store.updateStreaming(id: draftID, text: "overwritten")316        #expect(try await store.message(id: draftID)?.text == "Lighthouses guide ships at night")317        #expect(try await store.activePath(conversationID: conversationID).last?.id == draftID)318    }319320    @Test func streamingUpdatesAreCheap() async throws {321        let directory = try temporaryDirectory()322        defer { try? FileManager.default.removeItem(at: directory) }323        let store = try AstraStore(url: directory.appendingPathComponent("astra.sqlite"))324        let conversation = try await store.createConversation(model: gpt)325        try await store.appendUserMessage(conversationID: conversation.id, text: "go")326        let draft = try await store.beginAssistantMessage(conversationID: conversation.id, model: gpt)327        let text = String(repeating: "The quick brown fox jumps over the lazy dog. ", count: 450)   // about 20 000 characters328        let clock = ContinuousClock()329        let rounds = 200330        let elapsed = try await clock.measure {331            for round in 0..<rounds { try await store.updateStreaming(id: draft.id, text: text + String(round)) }332        }333        let perUpdate = elapsed / rounds334        print("updateStreaming (20 kB text, file database): \(perUpdate) per call")335        #expect(perUpdate < .milliseconds(20))336        let ftsRows = try await store.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM message_fts") }337        #expect(ftsRows == 1)   // only the user message: streaming text never touched the index338    }339340    @Test func bookmarks() async throws {341        let store = try makeStore()342        let a = try await store.createConversation(model: gpt)343        let b = try await store.createConversation(model: gpt)344        let one = try await store.exchange(a.id, "q", "keep this", at: 1)345        let two = try await store.exchange(b.id, "q", "and this", at: 5)346        #expect(try await store.toggleBookmark(messageID: one.assistant.id) == true)347        #expect(try await store.toggleBookmark(messageID: two.assistant.id) == true)348        #expect(try await store.bookmarks().map(\.text) == ["and this", "keep this"])349        #expect(try await store.bookmarks(conversationID: a.id).map(\.text) == ["keep this"])350        #expect(try await store.toggleBookmark(messageID: one.assistant.id) == false)351        #expect(try await store.bookmarks().map(\.text) == ["and this"])352        await #expect(throws: AstraStoreError.self) { try await store.toggleBookmark(messageID: "missing") }353    }354355    @Test func deletingASubtreeMovesTheActiveLeaf() async throws {356        let store = try makeStore()357        let conversation = try await store.createConversation(model: gpt, at: t(0))358        let first = try await store.exchange(conversation.id, "q1", "a1", at: 1)359        let second = try await store.exchange(conversation.id, "q2", "a2", at: 3)360        try await store.exchange(conversation.id, "q3", "a3", at: 5)361        let file = AttachmentDraft(kind: .file, filename: "f.bin", mimeType: "application/octet-stream", data: Data(repeating: 1, count: 64))362        try await store.addAttachment(messageID: second.user.id, file)363        let alternative = try await store.editAndResend(messageID: second.user.id, newText: "q2 alt", keepAttachments: false, at: t(2))364        try await store.selectBranch(messageID: second.user.id)365366        // Deleting a branch that is not showing leaves the active path alone.367        #expect(try await store.deleteMessageSubtree(messageID: alternative.id).rowsDeleted == 1)368        #expect(try await store.activePath(conversationID: conversation.id).count == 6)369        // Deleting the showing branch falls back to the parent.370        let result = try await store.deleteMessageSubtree(messageID: second.user.id)371        #expect(result.rowsDeleted == 4)372        #expect(result.bytesFreed >= 64)373        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q1", "a1"])374        #expect(try await store.attachmentStorageBytes() == 0)375        #expect(try await store.searchConversations("q3").isEmpty)376        // Deleting the only root empties the conversation.377        try await store.deleteMessageSubtree(messageID: first.user.id)378        #expect(try await store.conversation(id: conversation.id)?.activeLeafID == nil)379        #expect(try await store.messageCount(conversationID: conversation.id) == 0)380        try await store.exchange(conversation.id, "fresh", "start", at: 20)381        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["fresh", "start"])382    }383384    @Test func deletingTheActiveBranchSelectsTheRemainingSibling() async throws {385        let store = try makeStore()386        let conversation = try await store.createConversation(model: gpt, at: t(0))387        let pair = try await store.exchange(conversation.id, "q", "a1", at: 1)388        let second = try await store.regenerate(assistantMessageID: pair.assistant.id, at: t(5))389        try await store.finalizeAssistantMessage(id: second.id, MessageCompletion(text: "a2"), at: t(6))390        try await store.deleteMessageSubtree(messageID: second.id)391        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["q", "a1"])392    }393394    @Test func activePathOfFiveThousandMessagesIsFast() async throws {395        let store = try makeStore()396        let conversation = try await store.createConversation(model: gpt, at: t(0))397        let usage = TokenUsage(inputTokens: 1200, outputTokens: 300)398        for index in 0..<2500 {399            try await store.appendUserMessage(conversationID: conversation.id, text: "Question number \(index) about harbours and tides.", at: t(Double(index)))400            let draft = try await store.beginAssistantMessage(conversationID: conversation.id, model: gpt, at: t(Double(index) + 0.3))401            try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(text: "Answer number \(index), with a few sentences of text to decode.",402                                                                                      reportedModel: "gpt-test-2026", usage: usage,403                                                                                      cost: CostEstimate(amountUSD: 0.001, basis: .estimatedFromUsage),404                                                                                      timeToFirstToken: 0.3, totalTime: 1.2),405                                                     recordUsage: false, at: t(Double(index) + 0.6))406        }407        // A side branch in the middle must not disturb the walk.408        let middle = try await store.activePath(conversationID: conversation.id, last: 2500).first!409        let leaf = try #require(try await store.conversation(id: conversation.id)?.activeLeafID)410        let side = try await store.appendUserMessage(conversationID: conversation.id, text: "side branch", parentID: middle.id, at: t(9000))411        try await store.selectBranch(messageID: leaf)412413        let clock = ContinuousClock()414        var best = Duration.seconds(60)415        var path: [MessageRecord] = []416        for _ in 0..<5 {417            let elapsed = try await clock.measure { path = try await store.activePath(conversationID: conversation.id) }418            best = min(best, elapsed)419        }420        print("activePath, 5 000 messages: \(best) (best of 5)")421        #expect(path.count == 5000)422        #expect(path.first?.text == "Question number 0 about harbours and tides.")423        #expect(path.last?.text.hasPrefix("Answer number 2499") == true)424        #expect(zip(path, path.dropFirst()).allSatisfy { $1.parentID == $0.id })425        #expect(best < .milliseconds(500))426427        let tail = try await clock.measure { _ = try await store.activePath(conversationID: conversation.id, last: 40) }428        print("activePath(last: 40) in the same conversation: \(tail)")429        #expect(tail < .milliseconds(100))430        let select = try await clock.measure { _ = try await store.selectBranch(messageID: path[0].id) }431        print("selectBranch from the root of 5 000 messages: \(select)")432        // From the root, the most recent child at each level leads into the newer side branch.433        #expect(try await store.conversation(id: conversation.id)?.activeLeafID == side.id)434        // Deleting a conversation this deep must not hit SQLite's trigger recursion limit.435        let deletion = try await clock.measure { try await store.deleteConversation(id: conversation.id) }436        print("deleteConversation, 5 001 messages: \(deletion)")437        #expect(try await store.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM message") } == 0)438        #expect(try await store.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM message_fts") } == 0)439    }440441    @Test func deletingADeepSubtreeWorks() async throws {442        let store = try makeStore()443        let conversation = try await store.createConversation(model: gpt, at: t(0))444        var firstID = ""445        for index in 0..<3000 {446            let message = try await store.appendUserMessage(conversationID: conversation.id, text: "m\(index)", at: t(Double(index)))447            if index == 1 { firstID = message.id }448        }449        #expect(try await store.deleteMessageSubtree(messageID: firstID).rowsDeleted == 2999)450        #expect(try await store.activePath(conversationID: conversation.id).map(\.text) == ["m0"])451    }452453    @Test func manyTasksWriteConcurrently() async throws {454        let directory = try temporaryDirectory()455        defer { try? FileManager.default.removeItem(at: directory) }456        let store = try AstraStore(url: directory.appendingPathComponent("astra.sqlite"))457        let shared = try await store.createConversation(title: "shared", model: gpt)458        let writers = 24, perWriter = 20459        try await withThrowingTaskGroup(of: Void.self) { group in460            for writer in 0..<writers {461                group.addTask {462                    let own = try await store.createConversation(title: "writer \(writer)", model: gpt)463                    for index in 0..<perWriter {464                        try await store.appendUserMessage(conversationID: own.id, text: "w\(writer) m\(index)")465                        try await store.appendUserMessage(conversationID: shared.id, text: "shared w\(writer) m\(index)")466                        let draft = try await store.beginAssistantMessage(conversationID: own.id, model: gpt)467                        try await store.updateStreaming(id: draft.id, text: "partial")468                        try await store.finalizeAssistantMessage(id: draft.id, MessageCompletion(text: "done \(index)", usage: TokenUsage(inputTokens: 1, outputTokens: 1)))469                        try await store.recordDiagnostic(RequestDiagnostic(provider: .openAI, modelID: "gpt-test"))470                        try await store.setSetting("counter.\(writer)", index)471                        _ = try await store.conversations()472                        _ = try await store.searchConversations("shared")473                    }474                }475            }476            try await group.waitForAll()477        }478        #expect(try await store.conversationCount() == writers + 1)479        // Every append to the shared conversation chained onto the leaf of the moment: one single path, nothing lost, no fork.480        let path = try await store.activePath(conversationID: shared.id)481        #expect(path.count == writers * perWriter)482        #expect(try await store.branchPositions(conversationID: shared.id).isEmpty)483        #expect(Set(path.map(\.text)).count == writers * perWriter)484        for conversation in try await store.conversations() where conversation.id != shared.id {485            let own = try await store.activePath(conversationID: conversation.id)486            #expect(own.count == perWriter * 2)487            #expect(own.allSatisfy { $0.status == .complete })488        }489        #expect(try await store.usageRecords().count == writers * perWriter)490        #expect(try await store.diagnostics().count == writers * perWriter)491        #expect(try await store.settingKeys().count == writers)492        #expect(try await store.integrityCheck() == [])493        #expect(try await store.read { db in try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM pragma_foreign_key_check") } == 0)494    }495}496
Files main
Menu

Theme