diff --git a/CONTEXT.md b/CONTEXT.md index c8c0fa30..b211cb81 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -256,10 +256,20 @@ render fixup. **Conversation Render**: The token-only rendering contract — family message-forming plus chat-template -application, no pixel work — shared by the planner's re-render and the leaf probes, -identical to the shape prepare uses, so a probe render cannot drift from prepare's. +application, no pixel work — shared by the request edge, the planner's +re-render, and the leaf probes, identical to the shape prepare uses, so a probe +render cannot drift from prepare's. Since 2026-09 a module, not a convention: +one per-request value (`ConversationRender`) built at **Request Keying** where +instance truth lives, sealed for the settled **Cache Key Space**, whose render +verbs own the whole choreography — cache eligibility, the Render+Token Cache +resolve, the template fallback, the no-generation-prompt merged context — so a +call site can no longer wire an ingredient wrong (the issue #439 defect class). +The render cache stays the implementation below it. _Avoid_: re-render (unqualified), probe tokenization, per-call-site -`applyChatTemplate` (the rendering it standardizes, not a synonym for it). +`applyChatTemplate` (the rendering it standardizes, not a synonym for it); +RenderTokenSource (the dissolved predecessor — eligibility as a free-standing +value each call site wired by hand); per-site resolve-or-fallback ladders (the +retired shape). **Position Anchor**: The M-RoPE continuation state a warm-restored conversation resumes generation at — diff --git a/tesseract/Features/Agent/Benchmark/AgentCpuBenchRunner.swift b/tesseract/Features/Agent/Benchmark/AgentCpuBenchRunner.swift index d2c8a18b..514a3851 100644 --- a/tesseract/Features/Agent/Benchmark/AgentCpuBenchRunner.swift +++ b/tesseract/Features/Agent/Benchmark/AgentCpuBenchRunner.swift @@ -263,26 +263,19 @@ final class AgentCpuBenchRunner { log("FAIL: conversation build returned nil on \(fixtures[index].label)") throw NSError(domain: "AgentCpuBench", code: 2) } - let resolution = try RenderTokenCache.shared.resolve( - tokenizer: tokenizer, - messages: conversation.promptMessages, - tools: canonicalTools, - additionalContext: nil, - modelFingerprint: fingerprint + let render = Self.makeRender( + tokenizer: tokenizer, canonicalTools: canonicalTools, fingerprint: fingerprint ) - guard let resolution else { + guard let fullTokens = render.fullRender(messages: conversation.promptMessages) else { log("FAIL: resolve returned nil on \(fixtures[index].label)") throw NSError(domain: "AgentCpuBench", code: 1) } - fixtures[index].fullTokens = resolution.tokens + fixtures[index].fullTokens = fullTokens let boundaries = try PrefillPlanner.detectBoundaries( conversation: conversation, - toolSpecs: canonicalTools, promptStartsThinking: true, - tokenizer: tokenizer, keySpace: .identity(keyPath: fixtures[index].fullTokens), - renderContext: .canonical, - modelFingerprint: fingerprint + render: render ) if index == 0, let offset = boundaries.stablePrefixOffset { stablePrefixOffset = offset @@ -295,6 +288,24 @@ final class AgentCpuBenchRunner { ) } + /// The bench's **Conversation Render** — the exact request-edge value the + /// production keying phase builds for a text-only request, so the seed + /// resolve and both boundary detects measure the production verbs. + private static func makeRender( + tokenizer: any MLXLMCommon.Tokenizer, + canonicalTools: [ToolSpec]?, + fingerprint: String + ) -> ConversationRender { + ConversationRender.forTextOnlyRequest( + tokenizer: tokenizer, + toolSpecs: canonicalTools, + renderContext: .canonical, + hasMedia: false, + producesFlatTextTokens: true, + modelFingerprint: fingerprint + ) + } + // MARK: - Timed phases /// One pass over all seven phases for one turn; each phase's median-of-reps @@ -351,17 +362,18 @@ final class AgentCpuBenchRunner { ) } - // p4 — boundary detection, memo-warm steady state. + // p4 — boundary detection, memo-warm steady state. The render is + // loop-invariant setup, built before the timed span starts. + let render = Self.makeRender( + tokenizer: tokenizer, canonicalTools: canonicalTools, fingerprint: fingerprint + ) var p4 = 0.0 let p4Start = ContinuousClock.now _ = try PrefillPlanner.detectBoundaries( conversation: conversation, - toolSpecs: canonicalTools, promptStartsThinking: true, - tokenizer: tokenizer, keySpace: .identity(keyPath: fixture.fullTokens), - renderContext: .canonical, - modelFingerprint: fingerprint + render: render ) p4 = Self.ms(since: p4Start) diff --git a/tesseract/Features/Agent/LLMActor.swift b/tesseract/Features/Agent/LLMActor.swift index 9edfc397..e9c87c71 100644 --- a/tesseract/Features/Agent/LLMActor.swift +++ b/tesseract/Features/Agent/LLMActor.swift @@ -347,37 +347,30 @@ actor LLMActor { /// MLXLLM, the app-side ParoQuant processor) captured at load — so the /// dicts rendered here are the dicts the processor would render. /// - /// The eligibility decision goes through `RenderTokenSource`, the shared - /// home for the predicate: notably, a `nil` fingerprint BYPASSES rather - /// than resolving under a synthetic key, because the cache's repeat path - /// trusts (bytes, fingerprint) with no arbiter behind it. + /// The eligibility decision and resolve go through the **Conversation + /// Render**'s agent edge, the shared home for the choreography: notably, + /// a `nil` fingerprint BYPASSES rather than resolving under a synthetic + /// key, because the cache's repeat path trusts (bytes, fingerprint) with + /// no arbiter behind it. private static func prepareViaRenderTokenCache( context: ModelContext, input: UserInput, modelFingerprint: String? ) -> LMInput? { - let llmModel = context.model as? any LLMModel - let source = RenderTokenSource.forTextOnlyRequest( - hasMedia: !(input.images.isEmpty && input.videos.isEmpty && input.audios.isEmpty), - producesFlatTextTokens: llmModel != nil, - modelFingerprint: modelFingerprint - ) - guard let cacheFingerprint = source.cacheFingerprint, let llmModel else { - return nil - } - let messages = llmModel.messageGenerator(tokenizer: context.tokenizer).generate(from: input) + guard let llmModel = context.model as? any LLMModel else { return nil } guard - let resolution = try? RenderTokenCache.shared.resolve( + let tokens = ConversationRender.agentEdgeFullRender( tokenizer: context.tokenizer, - messages: messages, + messages: llmModel.messageGenerator(tokenizer: context.tokenizer) + .generate(from: input), tools: input.tools, additionalContext: input.additionalContext, - modelFingerprint: cacheFingerprint + hasMedia: !(input.images.isEmpty && input.videos.isEmpty && input.audios.isEmpty), + producesFlatTextTokens: true, + modelFingerprint: modelFingerprint ) - else { - return nil - } - return LMInput(tokens: MLXArray(resolution.tokens)) + else { return nil } + return LMInput(tokens: MLXArray(tokens)) } /// Thinking-loop safeguard continuation for the HTTP prefix-cache path. diff --git a/tesseract/Features/Agent/Views/ChatItemViews.swift b/tesseract/Features/Agent/Views/ChatItemViews.swift index 56487de8..11522700 100644 --- a/tesseract/Features/Agent/Views/ChatItemViews.swift +++ b/tesseract/Features/Agent/Views/ChatItemViews.swift @@ -117,23 +117,39 @@ struct AssistantPartView: View { } /// Assistant prose — the document body. Markdown by default; the toolbar -/// toggle falls back to plain text. +/// toggle falls back to plain text. The live row passes `isLive` to swap in +/// the chunked streaming renderers, whose publishes cost O(new tail); the +/// committed row renders whole, restoring one selection surface and full +/// markdown fidelity. One view owns the mode branch and the plain-text +/// modifier stack, so the live→committed hand-off cannot drift visually. struct AssistantProseView: View { let text: String + var isLive = false @Environment(SettingsManager.self) private var settings var body: some View { #if DEBUG - let _ = ChatViewPerf.signposter.emitEvent("AssistantProseView.body") + let _ = ChatViewPerf.signposter.emitEvent( + isLive ? "AssistantProseView.live" : "AssistantProseView.body") #endif if settings.agentUseMarkdown { - ChatMarkdownView(text: text) + if isLive { + ChunkedStreamingMarkdown(text: text) + } else { + ChatMarkdownView(text: text) + } } else { - Text(text.chatDisplayTrimmed) - .font(.system(size: chatBodyFontSize)) - .lineSpacing(chatLineSpacing) - .textSelection(.enabled) - .frame(maxWidth: .infinity, alignment: .leading) + Group { + if isLive { + ChunkedStreamingText(text: text) + } else { + Text(text.chatDisplayTrimmed) + } + } + .font(.system(size: chatBodyFontSize)) + .lineSpacing(chatLineSpacing) + .textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading) } } } @@ -471,7 +487,7 @@ struct LivePartView: View { #endif switch live.kind { case .text: - AssistantProseView(text: live.displayText) + AssistantProseView(text: live.displayText, isLive: true) case .thinking: LiveThinkingRowView(live: live) } diff --git a/tesseract/Features/Agent/Views/ChatMarkdownStyle.swift b/tesseract/Features/Agent/Views/ChatMarkdownStyle.swift index ac7a1e28..eafcc3f1 100644 --- a/tesseract/Features/Agent/Views/ChatMarkdownStyle.swift +++ b/tesseract/Features/Agent/Views/ChatMarkdownStyle.swift @@ -204,10 +204,26 @@ struct ChatMarkdownStyle: StructuredText.Style { let thematicBreakStyle: StructuredText.GitHubThematicBreakStyle = .gitHub } +/// The vertical gaps Textual's GitHub styles draw between blocks. Textual +/// keeps them as private literals inside the style bodies +/// (`GitHubParagraphStyle` bottom 16, `GitHubHeadingStyle` / +/// `GitHubThematicBreakStyle` top 24), so they cannot be imported — they are +/// mirrored here, beside the style bundle that picks those styles, and must +/// be re-checked whenever the Textual pin moves. `ChunkedStreamingMarkdown` +/// draws them at its chunk seams so a seam is indistinguishable from the gap +/// Textual would draw inside one document. +nonisolated enum ChatMarkdownBlockSpacing { + /// GitHub paragraph / code / table bottom spacing. + static let betweenBlocks: CGFloat = 16 + /// GitHub heading / thematic-break top spacing. + static let beforeHeading: CGFloat = 24 +} + /// The one way chat markdown is rendered: the style bundle above plus the /// copyable code blocks, the Code Accent highlighter, and the transcript type -/// size. The transcript (`AssistantProseView`) and the Markdown Gallery both -/// render through this view, so the gallery cannot drift from the chat. +/// size. The transcript (`AssistantProseView`), the live row's frozen chunks +/// (`ChunkedStreamingMarkdown`), and the Markdown Gallery all render through +/// this view, so no caller can drift from the chat. struct ChatMarkdownView: View { let text: String diff --git a/tesseract/Features/Agent/Views/ChatViewSupport.swift b/tesseract/Features/Agent/Views/ChatViewSupport.swift index cec3c520..1cc46de9 100644 --- a/tesseract/Features/Agent/Views/ChatViewSupport.swift +++ b/tesseract/Features/Agent/Views/ChatViewSupport.swift @@ -77,6 +77,16 @@ extension StringProtocol { } } +extension String { + /// `String.Index` for a UTF-8 byte offset from the start — O(1) on native + /// strings (the index stores the byte offset directly). Callers guarantee + /// the offset lands on a grapheme boundary; the chunk accumulators only + /// record offsets at line starts. + nonisolated func index(atUTF8Offset offset: Int) -> Index { + utf8.index(utf8.startIndex, offsetBy: offset) + } +} + extension ContentPart { /// Whether this part would render as an empty row: a whitespace-only text /// part — the model's cosmetic "\n\n" between tool calls. The stored diff --git a/tesseract/Features/Agent/Views/ChunkedStreamingMarkdown.swift b/tesseract/Features/Agent/Views/ChunkedStreamingMarkdown.swift new file mode 100644 index 00000000..b9656f36 --- /dev/null +++ b/tesseract/Features/Agent/Views/ChunkedStreamingMarkdown.swift @@ -0,0 +1,261 @@ +import SwiftUI + +// MARK: - Chunked streaming markdown + +/// Live-streaming markdown whose layout cost is O(new tail), not +/// O(accumulated document): completed block runs freeze into chunk +/// `ChatMarkdownView`s that SwiftUI never re-parses or re-measures (their +/// strings are append-only and compare by shared storage), so each publish +/// re-renders only the short live tail. This is the live text row's analog of +/// `ChunkedStreamingText` — without it, a long streaming answer re-typesets +/// the entire accumulated document on every publish +/// (`ResolvedStyledText.StringDrawing.sizeThatFits` pegs the main thread at +/// 100% once the answer passes a few KB). +/// +/// Chunks cut only at blank-line boundaries outside fenced code blocks and +/// never before an indented (4-column) continuation line, so no CommonMark +/// block that can span a blank line is ever split. Constructs that span +/// *cut* boundaries anyway — a loose list continuing after a blank line, a +/// reference link resolved by a later definition — render with a minor seam +/// mid-stream and self-correct the moment the part commits, because the +/// committed row renders the whole text through one `ChatMarkdownView`. +/// Text selection cannot cross chunk boundaries while the stream is live; +/// the committed row restores full selection. +struct ChunkedStreamingMarkdown: View { + let text: String + + /// Reference box, not a `@State` struct: the accumulator records scan + /// bookkeeping on every publish, and a `@State` write would schedule a + /// second body pass per publish just to note the watermark. A freeze + /// landing one render late is invisible — chunks + tail always + /// reassemble to the same text. + @State private var frozen = Box() + + private final class Box { + var accumulator = ChunkedMarkdownAccumulator() + } + + var body: some View { + let accumulator = frozen.accumulator + let tail = accumulator.liveTail(of: text) + // Spacing is per-seam (paragraph rhythm vs. heading headroom), so + // the stack carries none and each element pads its own top. Frozen + // seams were classified at freeze time; only the tail's seam is + // derived here, because its first line may still be streaming. + VStack(alignment: .leading, spacing: 0) { + ForEach(accumulator.chunks.indices, id: \.self) { index in + ChatMarkdownView(text: accumulator.chunks[index].text) + .padding(.top, accumulator.chunks[index].topSpacing) + } + ChatMarkdownView(text: String(tail)) + .padding( + .top, + accumulator.chunks.isEmpty + ? 0 : ChunkedMarkdownAccumulator.seamSpacing(before: tail)) + } + .onChange(of: text, initial: true) { _, newValue in + frozen.accumulator.freezeCompletedBlocks(of: newValue) + } + } +} + +// MARK: - Accumulator + +/// The chunking state behind `ChunkedStreamingMarkdown`, kept separately so +/// the cut rules are unit-testable. Same contract as +/// `ChunkedTextAccumulator`: the source text only ever *grows* by appending; +/// every non-append rewrite upstream shrinks it, so a shrink is the reset +/// signal. +/// +/// A cut lands at the start of a non-blank line that follows a blank line, +/// but never inside a fenced code block and never before a line indented 4+ +/// columns (an indented-code or loose-list continuation). Fence tracking is +/// deliberately approximate — the leading delimiter run of a line toggles +/// fence state per CommonMark's core rules, info strings aside — because a +/// misread fence only suppresses or misplaces a seam; it cannot corrupt the +/// text, and the committed row re-renders the document whole. +nonisolated struct ChunkedMarkdownAccumulator { + /// One frozen markdown chunk plus the seam above it, classified once at + /// freeze time so `body` never re-derives spacing for frozen content. + struct Chunk: Equatable { + let text: String + /// The vertical gap drawn above this chunk: Textual's spacing for + /// the chunk's lead block, or 0 for the first chunk. + let topSpacing: CGFloat + } + + /// Frozen chunks — append-only, never mutated afterward, so a chunk view + /// keyed by its index is stable for the life of the stream. The chunk + /// texts joined plus `liveTail` always equal the source text. + private(set) var chunks: [Chunk] = [] + /// UTF-8 length of the consumed source prefix. Always lands at a line + /// start, so re-deriving the index is grapheme-safe. + private(set) var consumedUTF8: Int = 0 + private var lastSeenUTF8: Int = 0 + + // Line-scanner state, persistent across appends so a line split over + // two deltas classifies exactly once. All byte-level: every structural + // character (space, tab, newline, `#`, fence delimiters) is ASCII, and + // cuts land at line starts, which are grapheme boundaries. + private var lineStartUTF8: Int = 0 + private var leadingColumns: Int = 0 + private var contentStarted: Bool = false + private var runByte: UInt8 = 0 + private var runLength: Int = 0 + private var runEnded: Bool = false + private var tailHasNonSpace: Bool = false + private var tailHasBacktick: Bool = false + private var previousLineBlank: Bool = false + private var inFence: Bool = false + private var fenceByte: UInt8 = 0 + private var fenceLength: Int = 0 + /// Start offset of the newest safe cut line seen so far (0 = none). + private var lastSafeCutUTF8: Int = 0 + + /// Freeze once the live tail outgrows this many UTF-8 bytes and a safe + /// cut exists. Smaller than `ChunkedTextAccumulator`'s threshold: the + /// markdown tail pays parse + typeset per publish, not just layout. A + /// single giant paragraph or fenced block never freezes mid-block; its + /// tail grows until the block completes. + static let freezeThresholdUTF8 = 2048 + + /// Everything past the frozen prefix — what the live chunk renders. + /// Non-mutating so `body` can call it; a text that shrank since the last + /// freeze renders whole until `freezeCompletedBlocks` resets. + func liveTail(of text: String) -> Substring { + guard consumedUTF8 > 0, text.utf8.count >= consumedUTF8 else { + return text[...] + } + return text[text.index(atUTF8Offset: consumedUTF8)...] + } + + /// Fold the latest full text: reset if it shrank (rewrite upstream), + /// scan the freshly appended bytes for new safe cuts, then freeze the + /// prefix up to the newest cut once the tail outgrows the threshold. + mutating func freezeCompletedBlocks(of text: String) { + let total = text.utf8.count + if total < lastSeenUTF8 { self = .init() } + + if lastSeenUTF8 < total { + scan(text, fromUTF8Offset: lastSeenUTF8) + } + lastSeenUTF8 = total + + guard total - consumedUTF8 > Self.freezeThresholdUTF8, + lastSafeCutUTF8 > consumedUTF8 + else { return } + + let start = text.index(atUTF8Offset: consumedUTF8) + let cut = text.index(atUTF8Offset: lastSafeCutUTF8) + let chunk = String(text[start.. CGFloat { + let firstLine = next.prefix(while: { $0 != "\n" }) + let indent = firstLine.prefix(while: { $0 == " " }).count + guard indent < 4 else { return ChatMarkdownBlockSpacing.betweenBlocks } + + let content = firstLine.dropFirst(indent) + if isHeading(content) || isThematicBreak(content) { + return ChatMarkdownBlockSpacing.beforeHeading + } + return ChatMarkdownBlockSpacing.betweenBlocks + } + + private static func isHeading(_ line: some StringProtocol) -> Bool { + let hashes = line.prefix(while: { $0 == "#" }) + guard (1...6).contains(hashes.count) else { return false } + let rest = line.dropFirst(hashes.count) + return rest.isEmpty || rest.first == " " || rest.first == "\t" + } + + private static func isThematicBreak(_ line: some StringProtocol) -> Bool { + let stripped = line.filter { $0 != " " && $0 != "\t" } + guard stripped.count >= 3, let marker = stripped.first, + marker == "-" || marker == "*" || marker == "_" + else { return false } + return stripped.allSatisfy { $0 == marker } + } + + // MARK: Line scanning + + /// Scan appended bytes, classifying each completed line (blank, fence + /// delimiter, content) and recording a safe cut at the start of every + /// non-blank, non-indented line that follows a blank line outside a + /// fence. O(delta) per publish. + private mutating func scan(_ text: String, fromUTF8Offset start: Int) { + let utf8 = text.utf8 + var offset = start + for byte in utf8[text.index(atUTF8Offset: start)...] { + if byte == 0x0A { + finishLine() + lineStartUTF8 = offset + 1 + } else if !contentStarted { + switch byte { + case 0x20: leadingColumns += 1 + case 0x09: leadingColumns += 4 + case 0x0D: break + default: + contentStarted = true + if previousLineBlank, !inFence, leadingColumns < 4 { + lastSafeCutUTF8 = lineStartUTF8 + } + runByte = byte + runLength = 1 + } + } else if !runEnded, byte == runByte { + runLength += 1 + } else { + runEnded = true + if byte != 0x20, byte != 0x09, byte != 0x0D { + tailHasNonSpace = true + if byte == 0x60 { tailHasBacktick = true } + } + } + offset += 1 + } + } + + /// A `\n` just arrived; classify the completed line and reset per-line + /// scanner state. + private mutating func finishLine() { + let isDelimiterRun = + (runByte == 0x60 || runByte == 0x7E) + && runLength >= 3 && leadingColumns <= 3 + if contentStarted, isDelimiterRun { + if inFence { + // A close fence: the same delimiter, at least as long, with + // nothing but whitespace after the run. + if runByte == fenceByte, runLength >= fenceLength, !tailHasNonSpace { + inFence = false + } + } else if runByte != 0x60 || !tailHasBacktick { + // An open fence. A backtick fence's info string cannot + // contain a backtick (that line is inline code, not a + // fence). + inFence = true + fenceByte = runByte + fenceLength = runLength + } + } + previousLineBlank = !contentStarted + leadingColumns = 0 + contentStarted = false + runByte = 0 + runLength = 0 + runEnded = false + tailHasNonSpace = false + tailHasBacktick = false + } +} diff --git a/tesseract/Features/Agent/Views/ChunkedStreamingText.swift b/tesseract/Features/Agent/Views/ChunkedStreamingText.swift index a67a0593..546471a2 100644 --- a/tesseract/Features/Agent/Views/ChunkedStreamingText.swift +++ b/tesseract/Features/Agent/Views/ChunkedStreamingText.swift @@ -96,7 +96,7 @@ nonisolated struct ChunkedTextAccumulator { guard consumedUTF8 > 0, text.utf8.count >= consumedUTF8 else { return text[...] } - return text[Self.index(text, atUTF8Offset: consumedUTF8)...] + return text[text.index(atUTF8Offset: consumedUTF8)...] } /// Fold the latest full text: reset if it shrank (rewrite upstream), @@ -111,7 +111,7 @@ nonisolated struct ChunkedTextAccumulator { if lastSeenUTF8 < total { let utf8 = text.utf8 var offset = lastSeenUTF8 - for byte in utf8[Self.index(text, atUTF8Offset: lastSeenUTF8)...] { + for byte in utf8[text.index(atUTF8Offset: lastSeenUTF8)...] { offset += 1 if byte == 0x0A { newlineEndUTF8 = offset } } @@ -122,8 +122,8 @@ nonisolated struct ChunkedTextAccumulator { newlineEndUTF8 > consumedUTF8 else { return } - let tailStart = Self.index(text, atUTF8Offset: consumedUTF8) - let cutEnd = Self.index(text, atUTF8Offset: newlineEndUTF8) + let tailStart = text.index(atUTF8Offset: consumedUTF8) + let cutEnd = text.index(atUTF8Offset: newlineEndUTF8) // `index(before:)` steps back one grapheme, so a CRLF pair drops // from the chunk whole. var chunk = text[tailStart.. String.Index { - text.utf8.index(text.utf8.startIndex, offsetBy: offset) - } } diff --git a/tesseract/Features/Server/ConversationRender.swift b/tesseract/Features/Server/ConversationRender.swift new file mode 100644 index 00000000..495ad916 --- /dev/null +++ b/tesseract/Features/Server/ConversationRender.swift @@ -0,0 +1,327 @@ +// +// ConversationRender.swift +// tesseract +// +// The **Conversation Render** contract (CONTEXT.md) as a module: the one +// home for token-only rendering — family message-forming plus chat-template +// application, no pixel work — shared by the request edge, the planner's +// last-user re-render, the leaf store's stored-conversation measure, and the +// admission builder's continuation probes. Each verb owns the whole +// choreography its call sites used to repeat by hand: cache-eligibility, +// the **Render+Token Cache** resolve, the `applyChatTemplate` fallback, and +// the `add_generation_prompt: false` merged-context derivation. +// +// Eligibility is decided at construction, from instance truth, once: +// a `nil` `cacheFingerprint` means "always render+encode in full" — the +// pre-C25 behavior. The cache never sees a synthetic key: an unknown model +// fingerprint bypasses rather than sharing a bucket, because the repeat +// path is the one resolve whose exactness rests on the key alone (a +// byte-identical render under the same fingerprint returns the cached +// tokens outright, with no empirical arbiter behind it). This absorbs +// `RenderTokenSource`, whose predicate had once been five different +// spellings across the C25–C31 seams (two disagreeing on the +// unknown-fingerprint case) — and whose *choreography* still was. +// Issue #439 / PR #449 was exactly that shape failing: one call site wiring +// the wrong ingredient (the request images instead of the instance-filtered +// list) into the shared predicate. Construction at the one place instance +// truth lives makes that class of defect unrepresentable. +// +// The value is built at the **Request Keying** edge (pre-key-space, from +// instance facts), *sealed* with the request's **Cache Key Space** once +// keying settles (image-bearing key spaces need the real token list for +// their placeholder runs, so a non-identity space clears the fingerprint), +// and enriched once more by the leaf store with the C31 base render. It +// rides `HTTPPrefixCacheGeneration` to the post-generation phases. +// +// Concurrency: holds the request's tokenizer, so it is `@unchecked +// Sendable` under the same discipline as `HTTPPrefixCacheGeneration`, which +// carries it — built and consumed on the LLM actor's isolation. One +// scheduling change from the pre-module call sites: the leaf store's +// stored-conversation render used to run inside a **Model Session** lease +// and now runs off it (a CPU-only render no longer serializes against the +// session), relying on the tokenizer's own thread-safety exactly as the +// planner's and builder's renders always have. +// + +import Foundation +import MLXLMCommon + +nonisolated struct ConversationRender: @unchecked Sendable { + + /// The request's tokenizer — exposed because sibling tokenizer-affine + /// work (`StablePrefixDetector`, the generation-prompt suffix encode) + /// legitimately shares it; the *render choreography* is what callers must + /// not re-open. + let tokenizer: any Tokenizer + + /// The request's canonicalized tool specs — one value for every render + /// of this request, so a probe render cannot drift from prepare's. + let toolSpecs: [ToolSpec]? + + /// The request's template render context; base and merged + /// `additionalContext` both derive from it, inside the verbs. + let renderContext: TemplateRenderContext + + /// The fingerprint every cache resolve keys under, or `nil` to bypass + /// the cache and render in full (see the header). Cleared only by + /// `sealed(for:)`. + private(set) var cacheFingerprint: String? + + /// The stored (base) conversation's render-space token list, when the + /// leaf store already computed the identical render this request (C31). + /// Only ever the base render — a continuation render is a different + /// conversation and is always computed. Set exclusively by + /// `carryingBaseRender(_:)`. + private(set) var baseRenderTokens: [Int]? + + // The `private` cache member keeps the synthesized memberwise init + // private too: outside construction goes through the eligibility + // constructors below, never field-by-field. + private let cache: RenderTokenCache + + // MARK: - Construction (the eligibility decision) + + /// The one spelling of the eligibility predicate, shared by the request + /// edge and the agent edge: engage the cache only for a media-free + /// request on a model whose processor emits a flat 1-D token list, and + /// only under a known fingerprint. + private static func eligibleFingerprint( + hasMedia: Bool, + producesFlatTextTokens: Bool, + modelFingerprint: String? + ) -> String? { + (!hasMedia && producesFlatTextTokens) ? modelFingerprint : nil + } + + /// The request-edge constructor: engage the cache only for a media-free + /// request on a model whose processor emits a flat 1-D token list. + /// + /// `producesFlatTextTokens` is the DIRECT property the cache path needs — + /// `LMInput(tokens:)` must reproduce what the processor would build, and + /// a vision container's text-only `prepare` emits 2D `[batch, seq]`. It + /// replaced the old `imageKeying == nil` proxy, which asked whether the + /// app RECOGNIZES a vision container — true of the then-only VLM family + /// by coincidence, and silently wrong for any VLM family added without + /// an image-keying rule. + /// + /// `hasMedia` must key on the INSTANCE-FILTERED image list (issue #439): + /// a dropped-image request is text-only by construction. + static func forTextOnlyRequest( + tokenizer: any Tokenizer, + toolSpecs: [ToolSpec]?, + renderContext: TemplateRenderContext, + hasMedia: Bool, + producesFlatTextTokens: Bool, + modelFingerprint: String?, + cache: RenderTokenCache = .shared + ) -> ConversationRender { + ConversationRender( + tokenizer: tokenizer, + toolSpecs: toolSpecs, + renderContext: renderContext, + cacheFingerprint: eligibleFingerprint( + hasMedia: hasMedia, + producesFlatTextTokens: producesFlatTextTokens, + modelFingerprint: modelFingerprint + ), + baseRenderTokens: nil, + cache: cache + ) + } + + /// A render that always runs in full — no cache participation, by + /// construction rather than by answering the eligibility questions with + /// literals. For sites with no request instance behind them: replay + /// telemetry probes, benchmarks, tests. + static func uncached( + tokenizer: any Tokenizer, + toolSpecs: [ToolSpec]? = nil, + renderContext: TemplateRenderContext = .canonical + ) -> ConversationRender { + ConversationRender( + tokenizer: tokenizer, + toolSpecs: toolSpecs, + renderContext: renderContext, + cacheFingerprint: nil, + baseRenderTokens: nil, + cache: .shared + ) + } + + /// Seal the edge-constructed value with the settled **Cache Key Space**: + /// cache resolves stay engaged only on an identity (text-only) space. + /// Image-bearing key spaces need the real token list for their + /// placeholder runs, so they always render in full. + func sealed(for keySpace: CacheKeySpace) -> ConversationRender { + guard !keySpace.isIdentity else { return self } + var copy = self + copy.cacheFingerprint = nil + return copy + } + + /// The C31 enrichment: carry the stored conversation's just-computed + /// render so the admission builder's base probe never re-runs the + /// identical computation. The single sanctioned way to plumb a render + /// between phases — only ever the base render. + func carryingBaseRender(_ tokens: [Int]) -> ConversationRender { + var copy = self + copy.baseRenderTokens = tokens + return copy + } + + // MARK: - Render verbs + + /// The request-edge full render (C25): resolve the whole conversation + /// through the cache, or `nil` — bypass, cold cache, non-rendering + /// tokenizer, or any render/encode failure — in which case the caller + /// falls back to its processor's `prepare`, which reproduces today's + /// error handling (the missing-template plain-text fallback stays in + /// the processor). The one verb whose fallback is model-affine and so + /// stays with the caller. `messages` is an autoclosure so a bypassing + /// render never pays the message-forming pass. + func fullRender(messages: @autoclosure () -> [[String: any Sendable]]) -> [Int]? { + guard let cacheFingerprint else { return nil } + return Self.resolveFull( + cache: cache, + tokenizer: tokenizer, + messages: messages(), + tools: toolSpecs, + additionalContext: renderContext.additionalContext(), + fingerprint: cacheFingerprint + ) + } + + /// The planner's last-user boundary render (C27): the conversation + /// truncated at a message index, rendered without a generation prompt. + /// Recovered as a verified trim of the entry the request-edge resolve + /// cached for this same conversation — `messages` are a prompt-message + /// prefix of it, so the entry's cumulative digest-chain head IS the + /// truncated chain (a bypassed or fallen-back edge leaves an older + /// entry, which the render arbiters reject; the assertion is a cost + /// hint, never a correctness input). Any inexactness falls back to the + /// full `applyChatTemplate`. Throws only what the fallback render + /// throws. + func lastUserPrefixRender(messages: [[String: any Sendable]]) throws -> [Int] { + try trimRecoveredRender(messages: messages, messagesAreEntryPrefix: true) + } + + /// A continuation of the cached conversation, rendered without a + /// generation prompt (C28): the stored conversation the leaf store + /// measures, and the admission builder's continuation probes — one verb, + /// because they are the identical computation. Recovered as a verified + /// trim+extension of the request-edge entry; any inexactness falls back + /// to the full `applyChatTemplate`. Throws only what the fallback render + /// throws. + func continuationRender(messages: [[String: any Sendable]]) throws -> [Int] { + try trimRecoveredRender(messages: messages, messagesAreEntryPrefix: false) + } + + /// The base (stored) conversation's render: the C31 plumbed tokens when + /// the leaf store already computed them this request, else the same + /// continuation render the plumbing short-circuits. + func baseRender(messages: [[String: any Sendable]]) throws -> [Int] { + try baseRenderTokens ?? continuationRender(messages: messages) + } + + /// The shared no-generation-prompt ladder behind the C27 and C28 verbs: + /// merged-context derivation, the trim-recovery resolve (against the + /// request-edge entry; `messagesAreEntryPrefix` selects the C27 + /// truncated form over the C28 tail-replacement), and the + /// `applyChatTemplate` fallback — one spelling, so the two verbs cannot + /// drift apart. + private func trimRecoveredRender( + messages: [[String: any Sendable]], + messagesAreEntryPrefix: Bool + ) throws -> [Int] { + let merged = renderContext.additionalContext( + merging: ["add_generation_prompt": false] + ) + if let cacheFingerprint { + let resolved: [Int]? = + messagesAreEntryPrefix + ? try? cache.resolveTruncated( + tokenizer: tokenizer, + messages: messages, + tools: toolSpecs, + baseAdditionalContext: renderContext.additionalContext(), + mergedAdditionalContext: merged, + modelFingerprint: cacheFingerprint, + messagesAreEntryPrefix: true + ) + : try? cache.resolveReplacingTail( + tokenizer: tokenizer, + messages: messages, + tools: toolSpecs, + baseAdditionalContext: renderContext.additionalContext(), + mergedAdditionalContext: merged, + modelFingerprint: cacheFingerprint + ) + if let resolved { + return resolved + } + } + return try tokenizer.applyChatTemplate( + messages: messages, + tools: toolSpecs, + additionalContext: merged + ) + } + + /// The one spelling of the C25 resolve body, shared by `fullRender` and + /// the agent edge (whose `additionalContext` is raw, not a + /// `TemplateRenderContext`). Absorbs every failure into `nil` — the + /// caller's processor fallback. + private static func resolveFull( + cache: RenderTokenCache, + tokenizer: any Tokenizer, + messages: [[String: any Sendable]], + tools: [ToolSpec]?, + additionalContext: [String: any Sendable]?, + fingerprint: String + ) -> [Int]? { + (try? cache.resolve( + tokenizer: tokenizer, + messages: messages, + tools: tools, + additionalContext: additionalContext, + modelFingerprint: fingerprint + ))?.tokens + } + + // MARK: - The agent edge + + /// The agent raw-generation edge (`LLMActor`), which has no + /// conversation value, no key space, and a raw `additionalContext` + /// instead of a `TemplateRenderContext` — the narrow static entry over + /// the same eligibility and resolve, so the fifth spelling shares this + /// home without pretending the contexts match. `nil` sends the caller + /// to its processor's `prepare`. `messages` is an autoclosure so an + /// ineligible request (media, 2D tokens, unknown fingerprint) never pays + /// the message-forming pass. + static func agentEdgeFullRender( + tokenizer: any Tokenizer, + messages: @autoclosure () -> [[String: any Sendable]], + tools: [ToolSpec]?, + additionalContext: [String: any Sendable]?, + hasMedia: Bool, + producesFlatTextTokens: Bool, + modelFingerprint: String?, + cache: RenderTokenCache = .shared + ) -> [Int]? { + guard + let fingerprint = eligibleFingerprint( + hasMedia: hasMedia, + producesFlatTextTokens: producesFlatTextTokens, + modelFingerprint: modelFingerprint + ) + else { return nil } + return resolveFull( + cache: cache, + tokenizer: tokenizer, + messages: messages(), + tools: tools, + additionalContext: additionalContext, + fingerprint: fingerprint + ) + } +} diff --git a/tesseract/Features/Server/LeafAdmissionBuilder.swift b/tesseract/Features/Server/LeafAdmissionBuilder.swift index 9d848f89..d32d6ccc 100644 --- a/tesseract/Features/Server/LeafAdmissionBuilder.swift +++ b/tesseract/Features/Server/LeafAdmissionBuilder.swift @@ -105,60 +105,33 @@ nonisolated enum LeafAdmissionBuilder { /// is not strictly shorter than the continuation (the appended turn added /// no tokens, so there is no distinct boundary to align to). /// - /// `renderTokens` carries both the C28 and the C31 plumbing: - /// - Its `cacheFingerprint` engages the C28 tail-replacement resolve for - /// both renders (identity key space, known fingerprint): post-generation, - /// the **Request Keying** phase's entry still holds this request's full - /// render, so each of these generation-prompt-OFF renders is recovered as - /// a verified trim+extension of that entry — one suffix encode instead of - /// two full re-encodes. A bypass, or any inexactness, runs today's - /// `applyChatTemplate`. - /// - Its `baseRenderTokens` is the base render's token list, already - /// computed this request by the **Leaf Store** phase's - /// `measureStoredTokenSequence` — the IDENTICAL computation (same - /// messages, tools, contexts, fingerprint, tokenizer, key-space guard; - /// verified in C28) — so the base render runs once per request. `nil` - /// computes it here, exactly as before. Only the base render is plumbed; - /// the continuation render is a different conversation and is always + /// `render` — the request's **Conversation Render** — carries both the + /// C28 and the C31 plumbing: + /// - Its `continuationRender` verb owns the C28 tail-replacement ladder + /// for both renders (identity key space, known fingerprint): + /// post-generation, the **Request Keying** phase's entry still holds + /// this request's full render, so each of these generation-prompt-OFF + /// renders is recovered as a verified trim+extension of that entry — + /// one suffix encode instead of two full re-encodes. A bypass, or any + /// inexactness, runs today's `applyChatTemplate`. + /// - Its `baseRender` serves the base render's token list when the + /// **Leaf Store** phase already computed it this request — the + /// IDENTICAL computation (same messages, tools, contexts, fingerprint, + /// tokenizer, key-space guard; verified in C28) — so the base render + /// runs once per request. Only the base render is ever plumbed; the + /// continuation render is a different conversation and is always /// computed. static func reusablePrefix( continuation: Continuation, storedConversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, - tokenizer: any Tokenizer, keySpace: CacheKeySpace, - renderContext: TemplateRenderContext = .canonical, - renderTokens: RenderTokenSource = .uncached + render: ConversationRender ) throws -> Result<[Int], CacheKeySpace.TranslationFailure>? { let baseMessages = storedConversation.promptMessages - let probeContext = renderContext.additionalContext( - merging: ["add_generation_prompt": false] + let storedTokens = try render.baseRender(messages: baseMessages) + let continuationTokens = try render.continuationRender( + messages: baseMessages + [continuation.probeMessage] ) - // One ladder for both renders: cache-resolve if eligible, else render - // in full. The cached resolve is keyed on the base (unmerged) context - // the Request Keying phase stored the entry under. - func tokens(for messages: [[String: any Sendable]]) throws -> [Int] { - if let cacheFingerprint = renderTokens.cacheFingerprint, - let resolved = try? RenderTokenCache.shared.resolveReplacingTail( - tokenizer: tokenizer, - messages: messages, - tools: toolSpecs, - baseAdditionalContext: renderContext.additionalContext(), - mergedAdditionalContext: probeContext, - modelFingerprint: cacheFingerprint - ) - { - return resolved - } - return try tokenizer.applyChatTemplate( - messages: messages, - tools: toolSpecs, - additionalContext: probeContext - ) - } - - let storedTokens = try renderTokens.baseRenderTokens ?? tokens(for: baseMessages) - let continuationTokens = try tokens(for: baseMessages + [continuation.probeMessage]) let common = zip(storedTokens, continuationTokens).prefix { $0 == $1 }.count guard common > 0, common <= storedTokens.count, common < continuationTokens.count else { @@ -199,12 +172,16 @@ nonisolated enum LeafAdmissionBuilder { /// checks here bound the abandoned work to one render+tokenize — without /// them a cancel would be a no-op against this synchronous body, and the /// preempting request would wait out the full remaining probe. + /// + /// `render` supplies the request's ingredients only — this probe is + /// deliberately CACHE-FREE (raw `applyChatTemplate`, never the render's + /// verbs): it runs detached and cancellable, and a resolve against the + /// live entry would neither observe the cancellation checks nor be + /// abandonable mid-render. static func futureSharedPrefix( storedConversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, - tokenizer: any Tokenizer, keySpace: CacheKeySpace, - renderContext: TemplateRenderContext = .canonical + render: ConversationRender ) throws -> Result<[Int], CacheKeySpace.TranslationFailure>? { try Task.checkCancellation() let baseMessages = storedConversation.promptMessages @@ -215,18 +192,18 @@ nonisolated enum LeafAdmissionBuilder { // walks. (`preserve_thinking` disables speculation today, so the // canonical default is what currently runs; this keeps the two in // step for the next flag that does not.) - let probeContext = renderContext.additionalContext( + let probeContext = render.renderContext.additionalContext( merging: ["add_generation_prompt": false] ) - let firstRender = try tokenizer.applyChatTemplate( + let firstRender = try render.tokenizer.applyChatTemplate( messages: baseMessages + [Continuation.userTurn.probeMessage], - tools: toolSpecs, + tools: render.toolSpecs, additionalContext: probeContext ) try Task.checkCancellation() - let secondRender = try tokenizer.applyChatTemplate( + let secondRender = try render.tokenizer.applyChatTemplate( messages: baseMessages + [divergentUserProbeMessage], - tools: toolSpecs, + tools: render.toolSpecs, additionalContext: probeContext ) @@ -248,22 +225,16 @@ nonisolated enum LeafAdmissionBuilder { private static func probeTokens( continuation: Continuation, storedConversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, - tokenizer: any Tokenizer, keySpace: CacheKeySpace, - renderContext: TemplateRenderContext, - renderTokens: RenderTokenSource + render: ConversationRender ) -> Probe { let probe: Result<[Int], CacheKeySpace.TranslationFailure>? do { probe = try reusablePrefix( continuation: continuation, storedConversation: storedConversation, - toolSpecs: toolSpecs, - tokenizer: tokenizer, keySpace: keySpace, - renderContext: renderContext, - renderTokens: renderTokens + render: render ) } catch { return .skip(.tokenizationFailed(error: error.localizedDescription)) @@ -289,21 +260,19 @@ nonisolated enum LeafAdmissionBuilder { /// offset-guard arithmetic, and emits a `LeafCapturePlan`. No live KV cache, /// no Metal — the actor executes the capture/`admit` from the decision. /// - /// `renderTokens` carries the cache eligibility and the C31 plumbing down - /// to the reusable-prefix probe: its `baseRenderTokens` is the stored - /// conversation's render-space token list the **Leaf Store** phase already - /// computed this request (the identical computation the probe's base render - /// would run), so the base render runs once per request. + /// `render` — the request's **Conversation Render** — carries the cache + /// eligibility and the C31 plumbing down to the reusable-prefix probe: + /// its `baseRender` serves the stored conversation's render-space token + /// list the **Leaf Store** phase already computed this request (the + /// identical computation the probe's base render would run), so the base + /// render runs once per request. static func plan( mode: BoundaryLeafMode, storedConversation: HTTPPrefixCacheConversation, storedTokens: [Int], - toolSpecs: [ToolSpec]?, transientBoundary: HybridCacheSnapshot?, - tokenizer: any Tokenizer, keySpace: CacheKeySpace, - renderContext: TemplateRenderContext = .canonical, - renderTokens: RenderTokenSource = .uncached, + render: ConversationRender, resolveBoundary: @Sendable ([Int]) async -> HybridCacheSnapshot? ) async -> LeafCapturePlan { switch mode { @@ -318,11 +287,8 @@ nonisolated enum LeafAdmissionBuilder { switch probeTokens( continuation: .toolResult, storedConversation: storedConversation, - toolSpecs: toolSpecs, - tokenizer: tokenizer, keySpace: keySpace, - renderContext: renderContext, - renderTokens: renderTokens + render: render ) { case .tokens(let translated): toolTokens = translated case .skip(let reason): return .skip(reason: reason) @@ -354,11 +320,8 @@ nonisolated enum LeafAdmissionBuilder { switch probeTokens( continuation: .userTurn, storedConversation: storedConversation, - toolSpecs: toolSpecs, - tokenizer: tokenizer, keySpace: keySpace, - renderContext: renderContext, - renderTokens: renderTokens + render: render ) { case .tokens(let translated): canonicalTokens = translated case .skip(let reason): return .skip(reason: reason) diff --git a/tesseract/Features/Server/LeafStorePhase.swift b/tesseract/Features/Server/LeafStorePhase.swift index b6741e84..88b76971 100644 --- a/tesseract/Features/Server/LeafStorePhase.swift +++ b/tesseract/Features/Server/LeafStorePhase.swift @@ -51,10 +51,8 @@ nonisolated enum LeafStorePhase { mlxStartBox: UnsafeSendableBox, conversation: HTTPPrefixCacheConversation, sessions: any ModelSessionProviding, - canonicalTools: [ToolSpec]?, requestID: UUID, prefixCache: PrefixCacheManager, - renderContext: TemplateRenderContext, promptStartsThinking: Bool, assistantText: String, assistantReasoning: String?, @@ -89,22 +87,25 @@ nonisolated enum LeafStorePhase { // translate into key space (identity for text-only). The translated // path is what every capture offset and admission below keys on — // length-equal to the prepared sequence, so key index == KV offset - // holds. - // C25–C31: one eligibility decision for every render this phase and - // the admission builder below make. - let renderTokenSource = RenderTokenSource.forIdentityKeySpace( - mlxStart.keySpace, - modelFingerprint: mlxStart.partitionKey.modelFingerprint - ) - guard - let storedRenderTokens = await measureStoredTokenSequence( - sessions: sessions, - conversation: storedConversation, - toolSpecs: canonicalTools, - renderContext: renderContext, - renderTokens: renderTokenSource + // holds. The **Conversation Render** owns the whole C28 ladder + // (cache-eligibility, tail-replacement resolve, template fallback); + // the guard/nil diagnostics behavior is unchanged. Raw prompt + // messages, so assistant `reasoning_content` and `tool_calls` + // survive template rendering. + guard let render = mlxStart.render else { + // The render is nil exactly for an Unkeyed Completion, which the + // guard above already returned on. + return result + } + let storedRenderTokens: [Int] + do { + storedRenderTokens = try render.continuationRender( + messages: storedConversation.promptMessages + ) + } catch { + Log.agent.warning( + "Stored token sequence measurement failed — error=\(error.localizedDescription)" ) - else { diagnosticsContext.logSkip( stage: "leafStore", reason: "tokenization-failed", @@ -156,21 +157,16 @@ nonisolated enum LeafStorePhase { case .directTool: mlxStart.transientLastMessageBoundarySnapshot case .canonical: mlxStart.transientLastUserBoundarySnapshot } - let leafTokenizer = try await sessions.withSession { $0.tokenizer } let leafPlan = await LeafAdmissionBuilder.plan( mode: boundaryMode, storedConversation: storedConversation, storedTokens: storedTokens, - toolSpecs: canonicalTools, transientBoundary: transientBoundary, - tokenizer: leafTokenizer, keySpace: mlxStart.keySpace, - renderContext: renderContext, - // C31: the base render the builder's probe would re-run is - // the identical computation `measureStoredTokenSequence` - // just performed for this request (verified in C28) — hand - // it in so the base render runs once per request. - renderTokens: renderTokenSource.withBaseRenderTokens(storedRenderTokens), + // C31: the stored render just computed above is the identical + // computation the builder's base probe would re-run (verified + // in C28) — carry it so the base render runs once per request. + render: render.carryingBaseRender(storedRenderTokens), resolveBoundary: { tokens in // Drive Snapshot Resolution inside the Model Session so // the SSD `loadSync` stays off-MainActor (ADR-0001). @@ -230,14 +226,13 @@ nonisolated enum LeafStorePhase { // its rewind span from the last-user boundary. let seedPlan = Self.speculativeSeedPlan( boundaryMode: boundaryMode, - renderContext: renderContext + renderContext: render.renderContext ) let pendingSeed: SpeculativeCanonicalPrefill.Seed? = seedPlan.map { plan in SpeculativeCanonicalPrefill.makeSeed( storedConversation: storedConversation, - toolSpecs: canonicalTools, - tokenizer: leafTokenizer, + render: render, keySpace: mlxStart.keySpace, partitionKey: mlxStart.partitionKey, prefillStepSize: mlxStart.prefillStepSize, @@ -247,7 +242,6 @@ nonisolated enum LeafStorePhase { ? boundaryStoredTokens.count : mlxStart.transientLastUserBoundarySnapshot? .tokenOffset ?? 0, - renderContext: renderContext, idleDelay: plan.idleDelay, ramOnlySpine: plan.ramOnlySpine, diagnostics: diagnosticsContext @@ -584,59 +578,6 @@ nonisolated enum LeafStorePhase { } } - // MARK: - Stored-token measurement - - /// Re-tokenize the stored conversation (prompt + generated response) and return - /// the flat token sequence. The HTTP prefix cache uses raw prompt messages here - /// so assistant `reasoning_content` and `tool_calls` survive template rendering. - /// Used for storing the leaf snapshot under the correct radix path. - /// Returns `nil` on tokenization failure. - /// - /// C28: when `renderTokens` is eligible (text-only identity key space, - /// known model fingerprint) the tail-replacement resolve recovers the - /// sequence as a verified trim+extension of the entry the **Request - /// Keying** phase cached for this request — one suffix encode instead of a - /// full re-encode. A bypass or any inexactness falls back to today's full - /// `applyChatTemplate`; the guard/nil behavior for diagnostics is - /// unchanged. - private static func measureStoredTokenSequence( - sessions: any ModelSessionProviding, - conversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, - renderContext: TemplateRenderContext = .canonical, - renderTokens: RenderTokenSource - ) async -> [Int]? { - do { - return try await sessions.withSession { session in - let mergedContext = renderContext.additionalContext( - merging: ["add_generation_prompt": false] - ) - if let cacheFingerprint = renderTokens.cacheFingerprint, - let resolved = try? RenderTokenCache.shared.resolveReplacingTail( - tokenizer: session.tokenizer, - messages: conversation.promptMessages, - tools: toolSpecs, - baseAdditionalContext: renderContext.additionalContext(), - mergedAdditionalContext: mergedContext, - modelFingerprint: cacheFingerprint - ) - { - return resolved - } - return try session.tokenizer.applyChatTemplate( - messages: conversation.promptMessages, - tools: toolSpecs, - additionalContext: mergedContext - ) - } - } catch { - Log.agent.warning( - "Stored token sequence measurement failed — error=\(error.localizedDescription)" - ) - return nil - } - } - // MARK: - Boundary executor /// What the boundary executor produced: the tuner record when the leaf diff --git a/tesseract/Features/Server/PrefillPlanner.swift b/tesseract/Features/Server/PrefillPlanner.swift index d6fadf46..02dd1d48 100644 --- a/tesseract/Features/Server/PrefillPlanner.swift +++ b/tesseract/Features/Server/PrefillPlanner.swift @@ -125,26 +125,24 @@ nonisolated enum PrefillPlanner { /// so the last-message boundary is found by encoding the known generation /// prompt string and subtracting it from the full token suffix. /// - /// `modelFingerprint` engages the C27 truncated resolve for the last-user - /// re-render (text key space only): the Request Keying phase just cached - /// the full render+tokens of this same conversation under that - /// fingerprint, so the truncated token list is recovered as a verified - /// trim of the stored entry. `nil` — or any inexactness — runs today's - /// `applyChatTemplate`. + /// `render` is the request's **Conversation Render** — its last-user + /// re-render engages the C27 truncated resolve internally (text key space + /// only, known fingerprint): the Request Keying phase just cached the + /// full render+tokens of this same conversation, so the truncated token + /// list is recovered as a verified trim of the stored entry, with any + /// inexactness falling back to the full `applyChatTemplate`. static func detectBoundaries( conversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, promptStartsThinking: Bool, - tokenizer: any Tokenizer, keySpace: CacheKeySpace, - renderContext: TemplateRenderContext = .canonical, - modelFingerprint: String? = nil + render: ConversationRender ) throws -> PrefillBoundaries { + let tokenizer = render.tokenizer let fullTokens = keySpace.keyPath let stablePrefixOffset = try StablePrefixDetector.detect( systemPrompt: conversation.systemPrompt, - toolSpecs: toolSpecs, - additionalContext: renderContext.additionalContext(), + toolSpecs: render.toolSpecs, + additionalContext: render.renderContext.additionalContext(), fullTokens: fullTokens, tokenizer: tokenizer ) @@ -177,43 +175,16 @@ nonisolated enum PrefillPlanner { toolDefinitionsDigest: conversation.toolDefinitionsDigest, templateContextDigest: conversation.templateContextDigest ) - let mergedContext = renderContext.additionalContext( - merging: ["add_generation_prompt": false]) - let renderTokens: [Int] - let source = RenderTokenSource.forIdentityKeySpace( - keySpace, modelFingerprint: modelFingerprint) - if let cacheFingerprint = source.cacheFingerprint, - let truncated = try? RenderTokenCache.shared.resolveTruncated( - tokenizer: tokenizer, - messages: userPrefixConversation.promptMessages, - tools: toolSpecs, - baseAdditionalContext: renderContext.additionalContext(), - mergedAdditionalContext: mergedContext, - modelFingerprint: cacheFingerprint, - // C31: when this request's Request Keying phase resolved - // through the cache it resolved the same `conversation` - // value, and the truncation above is a message prefix of - // it — so the entry's stored digest chain head IS the - // truncated chain (cumulative hashing). A bypassed or - // fallen-back Request Keying leaves an older entry, which - // the render arbiters then reject; the assertion is a cost - // hint, never a correctness input. - messagesAreEntryPrefix: true - ) - { - // C27: text-space requests recover the truncated render's - // tokens as a verified trim of the entry the Request Keying - // phase cached for this same conversation. Image-bearing - // (non-identity) key spaces keep the full render below — - // their placeholder runs need the real token list. - renderTokens = truncated - } else { - renderTokens = try tokenizer.applyChatTemplate( - messages: userPrefixConversation.promptMessages, - tools: toolSpecs, - additionalContext: mergedContext - ) - } + // C27: text-space requests recover the truncated render's tokens + // as a verified trim of the entry the Request Keying phase cached + // for this same conversation (the truncation above is a + // prompt-message prefix of it). Image-bearing (non-identity) key + // spaces render in full — their placeholder runs need the real + // token list; the sealed render bypasses the cache for them. The + // whole ladder — eligibility, resolve, fallback — is the verb's. + let renderTokens = try render.lastUserPrefixRender( + messages: userPrefixConversation.promptMessages + ) switch keySpace.translatedLength(renderTokens: renderTokens) { case .success(let keyLength): lastUserOffset = keyLength diff --git a/tesseract/Features/Server/RenderTokenCache.swift b/tesseract/Features/Server/RenderTokenCache.swift index de16bc9c..52811ab9 100644 --- a/tesseract/Features/Server/RenderTokenCache.swift +++ b/tesseract/Features/Server/RenderTokenCache.swift @@ -38,7 +38,7 @@ // This is the ONLY resolve with no empirical arbiter behind it — its // exactness rests entirely on (byte equality, model fingerprint), which is // why an unknown fingerprint bypasses the cache upstream rather than -// sharing a synthetic key (`RenderTokenSource`). +// sharing a synthetic key (`ConversationRender`). // // The cache keys on (modelFingerprint, templateHash, tools digest, // additional-context digest, per-message digest chain). `templateHash` is @@ -46,7 +46,7 @@ // path's `ModelFingerprint.computeFingerprint` already hashes // `tokenizer_config.json` / `chat_template.*`, so template identity is // covered twice. Images and vision-family models never reach here — every -// integration seam bypasses upstream of this type via `RenderTokenSource`. +// integration seam bypasses upstream of this type via `ConversationRender`. // // Experiment C27 — the **truncated resolve**: `PrefillPlanner` re-renders // every cache-aware request truncated at the last user message (with @@ -937,7 +937,7 @@ nonisolated final class RenderTokenCache: @unchecked Sendable { /// remains keyed. /// /// Memoized per model fingerprint. That is only sound because an unknown - /// fingerprint never reaches this type: `RenderTokenSource` bypasses the + /// fingerprint never reaches this type: `ConversationRender` bypasses the /// cache rather than passing a synthetic key, so two different models can /// never collide on one memo slot (they would then share a probe hash and /// the template-mismatch check would pass vacuously). diff --git a/tesseract/Features/Server/RenderTokenSource.swift b/tesseract/Features/Server/RenderTokenSource.swift deleted file mode 100644 index ab7be48d..00000000 --- a/tesseract/Features/Server/RenderTokenSource.swift +++ /dev/null @@ -1,83 +0,0 @@ -// -// RenderTokenSource.swift -// tesseract -// -// The single home for "may this render tokenize through the -// **Render+Token Cache**, and has its token list already been computed this -// request?" — one value replacing the five different spellings of that -// predicate the C25–C31 seams grew (`imageKeying == nil` + -// `?? "unfingerprinted"` on the request path, `keySpace.isIdentity, let -// modelFingerprint` on the planner/leaf paths, a ternary in the admission -// builder). Two of those five disagreed on the unknown-fingerprint case; -// this type makes the answer one decision made in one place. -// -// A `nil` `cacheFingerprint` means "always render+encode in full" — the -// pre-C25 behavior. The cache itself never sees a synthetic key: an unknown -// model fingerprint bypasses rather than sharing a bucket, because the -// repeat path is the one resolve whose exactness rests on the key alone (a -// byte-identical render under the same fingerprint returns the cached tokens -// outright, with no empirical arbiter behind it). -// - -import Foundation - -nonisolated struct RenderTokenSource: Sendable { - - /// The fingerprint to resolve under, or `nil` to bypass the cache. - let cacheFingerprint: String? - - /// The BASE conversation's render-space token list, when an earlier phase - /// of this same request already computed the identical render (C31). Only - /// ever the base render — a continuation render is a different - /// conversation and is always computed. - let baseRenderTokens: [Int]? - - /// Always render+encode in full: no cache, no plumbed render. - static let uncached = RenderTokenSource(cacheFingerprint: nil) - - init(cacheFingerprint: String?, baseRenderTokens: [Int]? = nil) { - self.cacheFingerprint = cacheFingerprint - self.baseRenderTokens = baseRenderTokens - } - - /// The planner / leaf-store / leaf-admission seams: engage the cache only - /// on an identity (text-only) **Cache Key Space** under a known model - /// fingerprint. Image-bearing key spaces need the real token list for - /// their placeholder runs, so they always render. - static func forIdentityKeySpace( - _ keySpace: CacheKeySpace, - modelFingerprint: String?, - baseRenderTokens: [Int]? = nil - ) -> RenderTokenSource { - RenderTokenSource( - cacheFingerprint: keySpace.isIdentity ? modelFingerprint : nil, - baseRenderTokens: baseRenderTokens - ) - } - - /// The request path (**Request Keying**, and the agent's - /// `startRawGeneration`): engage the cache only for a media-free request - /// on a model whose processor emits a flat 1-D token list. - /// - /// `producesFlatTextTokens` is the DIRECT property the cache path needs — - /// `LMInput(tokens:)` here must reproduce what the processor would build, - /// and a vision container's text-only `prepare` emits 2D `[batch, seq]`. - /// It replaces the old `imageKeying == nil` proxy, which asked whether the - /// app RECOGNIZES a vision container (`model_type` prefix `qwen3_5` plus a - /// `vision_config`) — true of today's only VLM family by coincidence, and - /// silently wrong for any VLM family added without an image-keying rule. - static func forTextOnlyRequest( - hasMedia: Bool, - producesFlatTextTokens: Bool, - modelFingerprint: String? - ) -> RenderTokenSource { - guard !hasMedia, producesFlatTextTokens else { return .uncached } - return RenderTokenSource(cacheFingerprint: modelFingerprint) - } - - /// Same eligibility, carrying a base render computed elsewhere this - /// request. - func withBaseRenderTokens(_ tokens: [Int]?) -> RenderTokenSource { - RenderTokenSource(cacheFingerprint: cacheFingerprint, baseRenderTokens: tokens) - } -} diff --git a/tesseract/Features/Server/RequestKeyingPhase.swift b/tesseract/Features/Server/RequestKeyingPhase.swift index e98d4f85..1eb1e44c 100644 --- a/tesseract/Features/Server/RequestKeyingPhase.swift +++ b/tesseract/Features/Server/RequestKeyingPhase.swift @@ -33,6 +33,10 @@ nonisolated enum RequestKeyingPhase { let tokenNDim: Int let partitionKey: CachePartitionKey let keySpace: CacheKeySpace + /// The request's **Conversation Render**, sealed for `keySpace` — + /// the one render authority every later phase (planner boundary, + /// leaf-store measure, admission probes) draws on. + let render: ConversationRender /// The recognized vision container mis-positions M-RoPE on any /// nil-state warm forward — text-only restores included — so the /// Position Anchor is seeded whenever the family is recognized AND @@ -114,8 +118,10 @@ nonisolated enum RequestKeyingPhase { // the text-only processor builds. Media, vision containers (whose // text-only `prepare` emits 2D tokens), an unknown model fingerprint, // non-rendering tokenizers, and any render/encode failure all fall back - // to the processor. The eligibility decision lives in - // `RenderTokenSource`, shared with the other four seams. + // to the processor. This is the ONE construction of the request's + // **Conversation Render** — eligibility decided here, where instance + // truth lives, then sealed for the key space below and threaded to + // every later render. // `hasMedia` keys on the INSTANCE-FILTERED list (issue #439): a // dropped-image request is text-only by construction — the processor // never sees the bytes, only the same content-array prompt the cache @@ -125,22 +131,17 @@ nonisolated enum RequestKeyingPhase { // `producesFlatTextTokens` is false), so real media still lands on the // processor via the flat-tokens guard; passing `keyedImages` keeps the // seam honest if that coupling ever changes. - let renderTokens = RenderTokenSource.forTextOnlyRequest( + let render = ConversationRender.forTextOnlyRequest( + tokenizer: session.tokenizer, + toolSpecs: canonicalTools, + renderContext: renderContext, hasMedia: !keyedImages.isEmpty, producesFlatTextTokens: producesFlatTextTokens, modelFingerprint: modelFingerprint ) let fullInput: LMInput - if let cacheFingerprint = renderTokens.cacheFingerprint, - let resolution = try? RenderTokenCache.shared.resolve( - tokenizer: session.tokenizer, - messages: conversation.promptMessages, - tools: canonicalTools, - additionalContext: renderContext.additionalContext(), - modelFingerprint: cacheFingerprint - ) - { - fullInput = LMInput(tokens: MLXArray(resolution.tokens)) + if let renderedTokens = render.fullRender(messages: conversation.promptMessages) { + fullInput = LMInput(tokens: MLXArray(renderedTokens)) } else { fullInput = try await session.prepare( UserInput( @@ -225,6 +226,7 @@ nonisolated enum RequestKeyingPhase { tokenNDim: tokenNDim, partitionKey: partitionKey, keySpace: keySpace, + render: render.sealed(for: keySpace), seedsPositionAnchor: effectiveImageKeying != nil )) } diff --git a/tesseract/Features/Server/ServerCompletion.swift b/tesseract/Features/Server/ServerCompletion.swift index eefda424..0ed9a263 100644 --- a/tesseract/Features/Server/ServerCompletion.swift +++ b/tesseract/Features/Server/ServerCompletion.swift @@ -76,6 +76,11 @@ nonisolated struct HTTPPrefixCacheGeneration: @unchecked Sendable { /// participation — the post-generation store flow must stay away from the /// radix tree entirely. let unkeyedReason: CacheKeySpace.UnkeyedReason? + /// The request's **Conversation Render**, sealed at Request Keying — the + /// one render authority the post-generation phases (leaf-store measure, + /// admission probes) draw on. `nil` exactly for an **Unkeyed + /// Completion**, which the leaf store leaves before any render. + let render: ConversationRender? /// Whether warm forwards must seed the **Position Anchor** (the loaded /// family is the recognized vision container). False for text models, /// where restored prefills keep their nil-state behavior. @@ -931,10 +936,8 @@ nonisolated final class ServerCompletion { mlxStartBox: mlxStartBox, conversation: conversation, sessions: sessions, - canonicalTools: canonicalTools, requestID: requestID, prefixCache: prefixCache, - renderContext: renderContext, promptStartsThinking: driver.startsInsideThinkBlock, assistantText: accumulator.text, assistantReasoning: clientStreams @@ -1044,30 +1047,24 @@ nonisolated final class ServerCompletion { // seed path already requires. if speculativeSeed == nil, Task.isCancelled, - mlxStart.unkeyedReason == nil, + // Keyed only: the render is nil exactly for an Unkeyed Completion. + let render = mlxStart.render, mlxStart.transientLastUserBoundarySnapshot != nil, !renderContext.preservesThinking { - // Session entry cannot fail with a non-throwing body; the - // hypothetical failure just skips the abort-arm seed. - let abortTokenizer = try? await sessions.withSession { $0.tokenizer } - if let abortTokenizer { - speculativeSeed = SpeculativeCanonicalPrefill.makeSeed( - storedConversation: conversation, - toolSpecs: canonicalTools, - tokenizer: abortTokenizer, - keySpace: mlxStart.keySpace, - partitionKey: mlxStart.partitionKey, - prefillStepSize: mlxStart.prefillStepSize, - ssdEnabled: mlxStart.ssdEnabled, - seedsPositionAnchor: mlxStart.seedsPositionAnchor, - canonicalLeafOffset: mlxStart.transientLastUserBoundarySnapshot? - .tokenOffset ?? 0, - renderContext: renderContext, - ramOnlySpine: true, - diagnostics: diagnosticsContext - ) - } + speculativeSeed = SpeculativeCanonicalPrefill.makeSeed( + storedConversation: conversation, + render: render, + keySpace: mlxStart.keySpace, + partitionKey: mlxStart.partitionKey, + prefillStepSize: mlxStart.prefillStepSize, + ssdEnabled: mlxStart.ssdEnabled, + seedsPositionAnchor: mlxStart.seedsPositionAnchor, + canonicalLeafOffset: mlxStart.transientLastUserBoundarySnapshot? + .tokenOffset ?? 0, + ramOnlySpine: true, + diagnostics: diagnosticsContext + ) } // Release this request's Budget Floor restore pins on every exit @@ -1191,12 +1188,9 @@ nonisolated final class ServerCompletion { // construction. let boundaries = try PrefillPlanner.detectBoundaries( conversation: conversation, - toolSpecs: canonicalTools, promptStartsThinking: promptStartsThinking, - tokenizer: session.tokenizer, keySpace: keySpace, - renderContext: renderContext, - modelFingerprint: modelFingerprint + render: keyed.render ) if let failure = boundaries.lastUserTranslationFailure { diagnosticsContext.logSkip( @@ -1435,6 +1429,7 @@ nonisolated final class ServerCompletion { fullTokenCount: fullTokenCount, tokenNDim: tokenNDim, keySpace: keySpace, + render: keyed.render, parameters: parameters, toolSpecs: canonicalTools, partitionKey: partitionKey, @@ -1811,6 +1806,7 @@ nonisolated final class ServerCompletion { fullTokens: fullTokens, keySpace: keySpace, unkeyedReason: nil, + render: keyed.render, seedsPositionAnchor: seedsPositionAnchor, snapshotAdmission: snapshotAdmission, ssdEnabled: ssdEnabled, @@ -2084,6 +2080,7 @@ nonisolated final class ServerCompletion { fullTokens: fullTokens, keySpace: .identity(keyPath: fullTokens), unkeyedReason: reason, + render: nil, seedsPositionAnchor: false, snapshotAdmission: nil, ssdEnabled: ssdEnabled, @@ -2112,6 +2109,7 @@ nonisolated final class ServerCompletion { fullTokenCount: Int, tokenNDim: Int, keySpace: CacheKeySpace, + render: ConversationRender, parameters: GenerateParameters, toolSpecs: [ToolSpec]?, partitionKey: CachePartitionKey, @@ -2131,6 +2129,7 @@ nonisolated final class ServerCompletion { fullTokenCount: fullTokenCount, tokenNDim: tokenNDim, keySpace: keySpace, + render: render, parameters: parameters, toolSpecs: toolSpecs, partitionKey: partitionKey, @@ -2164,6 +2163,7 @@ nonisolated final class ServerCompletion { fullTokenCount: Int, tokenNDim: Int, keySpace: CacheKeySpace, + render: ConversationRender, parameters: GenerateParameters, toolSpecs: [ToolSpec]?, partitionKey: CachePartitionKey, @@ -2246,6 +2246,7 @@ nonisolated final class ServerCompletion { fullTokens: fullTokens, keySpace: keySpace, unkeyedReason: nil, + render: render, seedsPositionAnchor: seedsPositionAnchor, snapshotAdmission: nil, ssdEnabled: ssdEnabled, diff --git a/tesseract/Features/Server/SpeculativePrefill.swift b/tesseract/Features/Server/SpeculativePrefill.swift index 832ad053..7cb39df1 100644 --- a/tesseract/Features/Server/SpeculativePrefill.swift +++ b/tesseract/Features/Server/SpeculativePrefill.swift @@ -106,15 +106,13 @@ nonisolated enum SpeculativeCanonicalPrefill { /// be `discard()`ed so the probe stops at its next cooperative check. static func makeSeed( storedConversation: HTTPPrefixCacheConversation, - toolSpecs: [ToolSpec]?, - tokenizer: any Tokenizer, + render: ConversationRender, keySpace: CacheKeySpace, partitionKey: CachePartitionKey, prefillStepSize: Int, ssdEnabled: Bool, seedsPositionAnchor: Bool, canonicalLeafOffset: Int, - renderContext: TemplateRenderContext = .canonical, idleDelay: Duration = .zero, ramOnlySpine: Bool = false, diagnostics: PrefixCacheDiagnostics.Context @@ -123,10 +121,8 @@ nonisolated enum SpeculativeCanonicalPrefill { let probe = Task.detached { try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: storedConversation, - toolSpecs: toolSpecs, - tokenizer: tokenizer, keySpace: keySpace, - renderContext: renderContext + render: render ) } return Seed( diff --git a/tesseract/Features/Server/Telemetry/CanonicalEchoFidelity.swift b/tesseract/Features/Server/Telemetry/CanonicalEchoFidelity.swift index 0b22b222..b14e742a 100644 --- a/tesseract/Features/Server/Telemetry/CanonicalEchoFidelity.swift +++ b/tesseract/Features/Server/Telemetry/CanonicalEchoFidelity.swift @@ -121,13 +121,18 @@ nonisolated enum CanonicalEchoFidelity { echoHasReasoning: echo.reasoning != nil ) + // Replay renders are always uncached — no live entry to resolve + // against, so every render runs in full through the same verbs the + // server uses. + let probeRender = ConversationRender.uncached( + tokenizer: tokenizer, toolSpecs: probeToolSpecs + ) let nextRender: [Int] do { - nextRender = try tokenizer.applyChatTemplate( - messages: next.promptMessages, - tools: nextToolSpecs, - additionalContext: ["add_generation_prompt": false] - ) + nextRender = + try ConversationRender + .uncached(tokenizer: tokenizer, toolSpecs: nextToolSpecs) + .continuationRender(messages: next.promptMessages) } catch { let verdict = Verdict.noPath(reason: "next-render-failed: \(error)") return BoundaryReport(boundary: boundary, leaf: verdict, speculation: nil) @@ -143,9 +148,8 @@ nonisolated enum CanonicalEchoFidelity { try LeafAdmissionBuilder.reusablePrefix( continuation: kind == .toolContinuation ? .toolResult : .userTurn, storedConversation: stored, - toolSpecs: probeToolSpecs, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: probeRender ) }, against: nextRender, @@ -170,9 +174,8 @@ nonisolated enum CanonicalEchoFidelity { of: { try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: probeToolSpecs, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: probeRender ) }, against: nextRender, diff --git a/tesseractTests/ChunkedStreamingMarkdownTests.swift b/tesseractTests/ChunkedStreamingMarkdownTests.swift new file mode 100644 index 00000000..2682dafc --- /dev/null +++ b/tesseractTests/ChunkedStreamingMarkdownTests.swift @@ -0,0 +1,211 @@ +import Foundation +import Testing + +@testable import Tesseract_Agent + +/// The chunking rules behind `ChunkedStreamingMarkdown`: block runs freeze +/// out of the live tail only at blank-line boundaries outside fenced code +/// blocks and never before an indented continuation, the frozen prefix is +/// append-only, and any shrink of the source text resets the state. +struct ChunkedMarkdownAccumulatorTests { + + private func makeMarkdown(paragraphs: Int) -> String { + (0.. before.count) + #expect(Array(acc.chunks.prefix(before.count)) == before) + expectReassembles(acc, text) + } + + @Test func growthBelowThresholdLeavesStateUntouched() { + var acc = ChunkedMarkdownAccumulator() + var text = makeMarkdown(paragraphs: 8) + acc.freezeCompletedBlocks(of: text) + let frozen = acc + + text += " more words in the same paragraph" + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks == frozen.chunks) + #expect(acc.consumedUTF8 == frozen.consumedUTF8) + expectReassembles(acc, text) + } + + @Test func blankLinesInsideFencedCodeNeverCut() { + var acc = ChunkedMarkdownAccumulator() + let fenced = + "```swift\n" + + String( + repeating: "let x = 1 // filler line\n\nlet y = 2 // more\n", + count: 60) + acc.freezeCompletedBlocks(of: fenced) + // Well past the threshold, but every blank line is inside the open + // fence — nothing may freeze. + #expect(acc.chunks.isEmpty) + #expect(String(acc.liveTail(of: fenced)) == fenced) + } + + @Test func cutsResumeAfterFenceCloses() { + var acc = ChunkedMarkdownAccumulator() + var text = + "```swift\n" + + String(repeating: "let x = 1\n\nlet y = 2\n", count: 150) + + "```\n\nafter the fence" + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks.count == 1) + #expect(String(acc.liveTail(of: text)) == "after the fence") + + text += " keeps growing" + acc.freezeCompletedBlocks(of: text) + expectReassembles(acc, text) + } + + @Test func tildeFenceClosesOnlyOnTilde() { + var acc = ChunkedMarkdownAccumulator() + // A ``` line inside a ~~~ fence is fence *content*, not a close. + let text = + "~~~\n```\n\n" + + String(repeating: "code line\n\n", count: 200) + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks.isEmpty) + } + + @Test func backtickRunWithTrailingBacktickIsNotAFence() { + var acc = ChunkedMarkdownAccumulator() + // "```x```" is inline code in a paragraph, not an open fence — + // blank lines after it must still cut. + let text = + "```inline```\n\n" + + makeMarkdown(paragraphs: 8) + acc.freezeCompletedBlocks(of: text) + #expect(!acc.chunks.isEmpty) + expectReassembles(acc, text) + } + + @Test func indentedContinuationIsNotACutPoint() { + var acc = ChunkedMarkdownAccumulator() + // An indented code block spans blank lines; the cut may not land on + // the indented continuation, only on the later unindented paragraph. + let indented = String(repeating: " indented code\n\n", count: 150) + let text = "intro paragraph\n\n" + indented + "closing paragraph" + acc.freezeCompletedBlocks(of: text) + #expect(String(acc.liveTail(of: text)) == "closing paragraph") + expectReassembles(acc, text) + } + + @Test func shrinkResetsAndRechunksFromScratch() { + var acc = ChunkedMarkdownAccumulator() + let long = makeMarkdown(paragraphs: 20) + acc.freezeCompletedBlocks(of: long) + #expect(!acc.chunks.isEmpty) + + let replacement = "safe prefix only" + acc.freezeCompletedBlocks(of: replacement) + #expect(acc.chunks.isEmpty) + #expect(String(acc.liveTail(of: replacement)) == replacement) + } + + @Test func liveTailIsWholeTextWhenStaleStateExceedsIt() { + var acc = ChunkedMarkdownAccumulator() + let long = makeMarkdown(paragraphs: 20) + acc.freezeCompletedBlocks(of: long) + + let shorter = "tiny" + #expect(String(acc.liveTail(of: shorter)) == shorter) + } + + @Test func multiByteContentCutsOnCharacterBoundaries() { + var acc = ChunkedMarkdownAccumulator() + var text = String(repeating: "héllo wörld 🌍✨\n\n", count: 200) + acc.freezeCompletedBlocks(of: text) + #expect(!acc.chunks.isEmpty) + expectReassembles(acc, text) + + text += "más🎈" + acc.freezeCompletedBlocks(of: text) + #expect(acc.liveTail(of: text).hasSuffix("más🎈")) + } + + @Test func singleGiantParagraphNeverFreezesButStaysRenderable() { + var acc = ChunkedMarkdownAccumulator() + let text = String(repeating: "x", count: 20_000) + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks.isEmpty) + #expect(String(acc.liveTail(of: text)) == text) + } + + // MARK: Seam spacing + + @Test func frozenChunkRecordsSeamSpacingForItsLeadBlock() { + var acc = ChunkedMarkdownAccumulator() + var text = makeMarkdown(paragraphs: 8) + "\n\n# Title" + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks.count == 1) + #expect(acc.chunks.first?.topSpacing == 0) + #expect(String(acc.liveTail(of: text)) == "# Title") + + text += "\n\n" + makeMarkdown(paragraphs: 8) + acc.freezeCompletedBlocks(of: text) + #expect(acc.chunks.count == 2) + #expect(acc.chunks[1].text.hasPrefix("# Title")) + #expect(acc.chunks[1].topSpacing == ChatMarkdownBlockSpacing.beforeHeading) + expectReassembles(acc, text) + } + + @Test func seamSpacingMatchesBlockTopSpacing() { + let heading = ChatMarkdownBlockSpacing.beforeHeading + let base = ChatMarkdownBlockSpacing.betweenBlocks + + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "# Title") == heading) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "###### h6\nbody") == heading) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "---") == heading) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "- - -") == heading) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "***") == heading) + + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "plain paragraph") == base) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "####### seven") == base) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "#tag no space") == base) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "- list item") == base) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: " # indented code") == base) + #expect(ChunkedMarkdownAccumulator.seamSpacing(before: "***bold*** text") == base) + } +} diff --git a/tesseractTests/LeafAdmissionBuilderTests.swift b/tesseractTests/LeafAdmissionBuilderTests.swift index c14bc26f..78ff1d23 100644 --- a/tesseractTests/LeafAdmissionBuilderTests.swift +++ b/tesseractTests/LeafAdmissionBuilderTests.swift @@ -35,9 +35,8 @@ import MLXLMCommon let prefix = try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) // The reusable prefix is exactly the stored turn's own render — the // synthetic user continuation is excluded. @@ -52,9 +51,8 @@ import MLXLMCommon let prefix = try LeafAdmissionBuilder.reusablePrefix( continuation: .toolResult, storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) #expect(try prefix?.get() == (try render(stored))) } @@ -70,9 +68,8 @@ import MLXLMCommon let prefix = try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: keySpace + keySpace: keySpace, + render: makeRender(tokenizer) ) // The probe runs in render space (the stored turn's own render, as in // the text-only probes) and the shared prefix comes back translated: @@ -91,9 +88,8 @@ import MLXLMCommon let prefix = try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: empty, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) #expect(prefix == nil) } @@ -112,18 +108,14 @@ import MLXLMCommon let computed = try LeafAdmissionBuilder.reusablePrefix( continuation: continuation, storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) let plumbed = try LeafAdmissionBuilder.reusablePrefix( continuation: continuation, storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity(), - renderTokens: RenderTokenSource( - cacheFingerprint: nil, baseRenderTokens: render(stored)) + render: makeRender(tokenizer, base: render(stored)) ) #expect(try plumbed?.get() == (try computed?.get())) #expect(try plumbed?.get() == (try render(stored))) @@ -136,19 +128,18 @@ import MLXLMCommon let stored = toolTurn() let baseRender = try render(stored) let toolTokens = try LeafAdmissionBuilder.reusablePrefix( - continuation: .toolResult, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity() + continuation: .toolResult, + storedConversation: stored, + keySpace: .identity(), + render: makeRender(tokenizer) )!.get() let plumbed = await LeafAdmissionBuilder.plan( mode: .directTool, storedConversation: stored, storedTokens: toolTokens, - toolSpecs: nil, transientBoundary: boundary(offset: 5), - tokenizer: tokenizer, keySpace: .identity(), - renderTokens: RenderTokenSource( - cacheFingerprint: nil, baseRenderTokens: baseRender), + render: makeRender(tokenizer, base: baseRender), resolveBoundary: noResolvedBoundary ) guard case .fromBoundary(let b, let tokens) = plumbed else { @@ -168,9 +159,8 @@ import MLXLMCommon ]) let future = try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) // The two probe contents diverge at their first character, so the // shared path is the stored render plus exactly the next user turn's @@ -195,16 +185,14 @@ import MLXLMCommon try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: stored, - toolSpecs: nil, - tokenizer: strippingTokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(strippingTokenizer) )?.get()) let future = try #require( try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: strippingTokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(strippingTokenizer) )?.get()) // The canonical leaf path stops at the strip divergence (the start of @@ -244,9 +232,8 @@ import MLXLMCommon do { _ = try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer) ) return false } catch is CancellationError { @@ -279,17 +266,17 @@ import MLXLMCommon let canonicalFuture = try #require( try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: thinkingTokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(thinkingTokenizer) )?.get()) let preservedFuture = try #require( try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: thinkingTokenizer, keySpace: .identity(), - renderContext: TemplateRenderContext(flags: [.preserveThinking]) + render: ConversationRender.uncached( + tokenizer: thinkingTokenizer, + renderContext: TemplateRenderContext(flags: [.preserveThinking]) + ) )?.get()) // Preserve-Thinking keeps the stored turn's reasoning span that the @@ -326,17 +313,18 @@ import MLXLMCommon @Test func directToolWithUsableBoundaryAndConvergingProbePlansFromBoundary() async throws { let stored = toolTurn() let toolTokens = try LeafAdmissionBuilder.reusablePrefix( - continuation: .toolResult, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity() + continuation: .toolResult, + storedConversation: stored, + keySpace: .identity(), + render: makeRender(tokenizer) )!.get() let plan = await LeafAdmissionBuilder.plan( mode: .directTool, storedConversation: stored, storedTokens: toolTokens, - toolSpecs: nil, transientBoundary: boundary(offset: 5), - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .fromBoundary(let b, let tokens) = plan else { @@ -352,10 +340,9 @@ import MLXLMCommon mode: .directTool, storedConversation: toolTurn(), storedTokens: [1, 2, 3], - toolSpecs: nil, transientBoundary: nil, - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -372,10 +359,9 @@ import MLXLMCommon mode: .directTool, storedConversation: HTTPPrefixCacheConversation(systemPrompt: nil, messages: []), storedTokens: [1, 2, 3], - toolSpecs: nil, transientBoundary: boundary(offset: 5), - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -388,18 +374,19 @@ import MLXLMCommon @Test func directToolWithEmptyResidualSkipsAtOrBeforeBoundary() async throws { let stored = toolTurn() let toolTokens = try LeafAdmissionBuilder.reusablePrefix( - continuation: .toolResult, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity() + continuation: .toolResult, + storedConversation: stored, + keySpace: .identity(), + render: makeRender(tokenizer) )!.get() // Boundary sits at the end of the tool render: the residual is empty. let plan = await LeafAdmissionBuilder.plan( mode: .directTool, storedConversation: stored, storedTokens: toolTokens, - toolSpecs: nil, transientBoundary: boundary(offset: toolTokens.count), - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -428,10 +415,9 @@ import MLXLMCommon mode: .directTool, storedConversation: stored, storedTokens: [1, 2, 3], - toolSpecs: nil, transientBoundary: boundary(offset: 3), - tokenizer: tokenizer, keySpace: keySpace, + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -456,8 +442,10 @@ import MLXLMCommon ]) let keySpace = try FakeChatMLTokenizer.keySpace(for: stored, runLengths: [4]) let canonical = try LeafAdmissionBuilder.reusablePrefix( - continuation: .userTurn, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: keySpace + continuation: .userTurn, + storedConversation: stored, + keySpace: keySpace, + render: makeRender(tokenizer) )!.get() // The transient boundary sits inside the image prefix; the resolver's // snapshot past the warm offset is chosen instead. @@ -466,10 +454,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: boundary(offset: 3), - tokenizer: tokenizer, keySpace: keySpace, + render: makeRender(tokenizer), resolveBoundary: { _ in self.boundary(offset: resolvedOffset) } ) guard case .fromBoundary(let b, let tokens) = plan else { @@ -490,8 +477,10 @@ import MLXLMCommon ]) let keySpace = try FakeChatMLTokenizer.keySpace(for: stored, runLengths: [4]) let canonical = try LeafAdmissionBuilder.reusablePrefix( - continuation: .userTurn, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: keySpace + continuation: .userTurn, + storedConversation: stored, + keySpace: keySpace, + render: makeRender(tokenizer) )!.get() // Both the transient boundary and the resolved snapshot sit inside the // image prefix — there is no usable restore boundary. @@ -499,10 +488,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: boundary(offset: 3), - tokenizer: tokenizer, keySpace: keySpace, + render: makeRender(tokenizer), resolveBoundary: { _ in self.boundary(offset: 2) } ) guard case .skip(let reason) = plan else { @@ -533,10 +521,9 @@ import MLXLMCommon mode: .directTool, storedConversation: stored, storedTokens: [1, 2, 3], - toolSpecs: nil, transientBoundary: boundary(offset: 1), - tokenizer: tokenizer, keySpace: keySpace, + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -561,8 +548,10 @@ import MLXLMCommon private func canonicalPrefix(_ stored: HTTPPrefixCacheConversation) throws -> [Int] { try LeafAdmissionBuilder.reusablePrefix( - continuation: .userTurn, storedConversation: stored, toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity() + continuation: .userTurn, + storedConversation: stored, + keySpace: .identity(), + render: makeRender(tokenizer) )!.get() } @@ -573,10 +562,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: boundary(offset: 4), - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .fromBoundary(let b, let tokens) = plan else { @@ -594,10 +582,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: nil, - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: { _ in self.boundary(offset: 7) } ) guard case .fromBoundary(let b, let tokens) = plan else { @@ -615,10 +602,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: nil, - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { @@ -638,10 +624,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: canonical, - toolSpecs: nil, transientBoundary: nil, - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: { _ in self.boundary(offset: canonical.count) } ) guard case .skip(let reason) = plan else { @@ -660,10 +645,9 @@ import MLXLMCommon mode: .canonical, storedConversation: stored, storedTokens: [1, 2], - toolSpecs: nil, transientBoundary: boundary(offset: 4), - tokenizer: tokenizer, keySpace: .identity(), + render: makeRender(tokenizer), resolveBoundary: noResolvedBoundary ) guard case .skip(let reason) = plan else { diff --git a/tesseractTests/PrefillPlannerTests.swift b/tesseractTests/PrefillPlannerTests.swift index 2bc6ddfb..20a56125 100644 --- a/tesseractTests/PrefillPlannerTests.swift +++ b/tesseractTests/PrefillPlannerTests.swift @@ -317,10 +317,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) // The two probes diverge at the user content, so the boundary is the @@ -337,10 +336,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) #expect(boundaries.stablePrefixOffset == nil) } @@ -356,10 +354,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) let genPromptBytes = FakeChatMLTokenizer.generationPrompt(thinking: true).utf8.count @@ -375,10 +372,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: false, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) let genPromptBytes = FakeChatMLTokenizer.generationPrompt(thinking: false).utf8.count @@ -396,10 +392,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: false, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) #expect(boundaries.lastMessageOffset == nil) } @@ -416,10 +411,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) // The re-render stops after the user turn — it excludes the trailing @@ -441,10 +435,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: .identity(keyPath: tokens) + keySpace: .identity(keyPath: tokens), + render: makeRender(tokenizer) ) #expect(boundaries.lastUserOffset == nil) } @@ -466,10 +459,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: keySpace + keySpace: keySpace, + render: makeRender(tokenizer) ) // The re-render up to the user turn carries one single-pad placeholder; @@ -524,10 +516,9 @@ import MLXLMCommon let boundaries = try PrefillPlanner.detectBoundaries( conversation: conv, - toolSpecs: nil, promptStartsThinking: true, - tokenizer: tokenizer, - keySpace: keySpace + keySpace: keySpace, + render: makeRender(tokenizer) ) #expect(boundaries.lastUserOffset == nil) diff --git a/tesseractTests/RenderTokenCacheRealTests.swift b/tesseractTests/RenderTokenCacheRealTests.swift index c7cf9954..b3966714 100644 --- a/tesseractTests/RenderTokenCacheRealTests.swift +++ b/tesseractTests/RenderTokenCacheRealTests.swift @@ -679,10 +679,10 @@ struct RenderTokenCacheReplacingFakeTests { /// The **Leaf Admission Builder**'s reusable-prefix probe routed through the /// C28 tail-replacement resolve: with a fingerprint and an identity key /// space, both probe renders recover from the entry the request cached — and -/// the probe result is identical to the uncached path. Serialized: the suite -/// drives the process-global `RenderTokenCache.shared`. -@Suite(.serialized) -struct LeafAdmissionCachePathTests { +/// the probe result is identical to the uncached path. Each test injects its +/// own private `RenderTokenCache` through the render's `cache:` seam, so the +/// suite never touches the process-global `.shared`. +@Suite struct LeafAdmissionCachePathTests { private static let fingerprint = "fake-model" @@ -696,9 +696,7 @@ struct LeafAdmissionCachePathTests { @Test func reusablePrefixServedByTheCacheMatchesTheUncachedProbe() throws { let tokenizer = Self.tokenizer() - let cache = RenderTokenCache.shared - cache.reset() - defer { cache.reset() } + let cache = RenderTokenCache() // The request's entry: the conversation WITHOUT its assistant turn, // rendered with the generation prompt — exactly what the Request @@ -717,18 +715,15 @@ struct LeafAdmissionCachePathTests { try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: storedConversation, - toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity(), - renderTokens: RenderTokenSource(cacheFingerprint: Self.fingerprint) + render: makeRender(tokenizer, fingerprint: Self.fingerprint, cache: cache) )?.get()) let uncached = try #require( try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: storedConversation, - toolSpecs: nil, - tokenizer: tokenizer, - keySpace: .identity() + keySpace: .identity(), + render: makeRender(tokenizer, cache: cache) )?.get()) #expect(cached == uncached) // Both probe renders (stored + continuation) came off the cache. @@ -740,9 +735,7 @@ struct LeafAdmissionCachePathTests { /// construction. @Test func reusablePrefixFallsBackWithoutACachedEntry() throws { let tokenizer = Self.tokenizer() - let cache = RenderTokenCache.shared - cache.reset() - defer { cache.reset() } + let cache = RenderTokenCache() let storedConversation = HTTPPrefixCacheConversation( systemPrompt: "You are helpful.", @@ -753,10 +746,8 @@ struct LeafAdmissionCachePathTests { _ = try LeafAdmissionBuilder.reusablePrefix( continuation: .userTurn, storedConversation: storedConversation, - toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity(), - renderTokens: RenderTokenSource(cacheFingerprint: "never-stored") + render: makeRender(tokenizer, fingerprint: "never-stored", cache: cache) )?.get() #expect(cache.statsSnapshot().replacedHits == 0) #expect(cache.statsSnapshot().replacedFallbacks == 2) diff --git a/tesseractTests/RenderTokenCacheTestSupport.swift b/tesseractTests/RenderTokenCacheTestSupport.swift index b7b717d2..208465e3 100644 --- a/tesseractTests/RenderTokenCacheTestSupport.swift +++ b/tesseractTests/RenderTokenCacheTestSupport.swift @@ -145,3 +145,30 @@ extension Array { indices.contains(index) ? self[index] : nil } } + +// MARK: - Shared Conversation Render fixture + +/// The one test spelling of a **Conversation Render**: built through the +/// production request-edge constructor, uncached unless a `fingerprint` is +/// given, with the C31 base render optionally carried. The eligibility knobs +/// default to the eligible text-only shape; the eligibility suite flips them. +nonisolated func makeRender( + _ tokenizer: any MLXLMCommon.Tokenizer, + toolSpecs: [ToolSpec]? = nil, + hasMedia: Bool = false, + producesFlatTextTokens: Bool = true, + fingerprint: String? = nil, + base: [Int]? = nil, + cache: RenderTokenCache = .shared +) -> ConversationRender { + let render = ConversationRender.forTextOnlyRequest( + tokenizer: tokenizer, + toolSpecs: toolSpecs, + renderContext: .canonical, + hasMedia: hasMedia, + producesFlatTextTokens: producesFlatTextTokens, + modelFingerprint: fingerprint, + cache: cache + ) + return base.map { render.carryingBaseRender($0) } ?? render +} diff --git a/tesseractTests/RenderTokenCacheTests.swift b/tesseractTests/RenderTokenCacheTests.swift index 692bf113..432d25fb 100644 --- a/tesseractTests/RenderTokenCacheTests.swift +++ b/tesseractTests/RenderTokenCacheTests.swift @@ -288,55 +288,64 @@ struct RenderTokenCacheFakeTests { // MARK: - Cache eligibility -/// `RenderTokenSource` is the single home for "may this render tokenize -/// through the cache" — the predicate five seams used to spell five ways, two -/// of which disagreed on the unknown-fingerprint case. -struct RenderTokenSourceTests { +/// The **Conversation Render** owns cache eligibility — decided once at its +/// request-edge construction and re-checked at key-space sealing; the +/// predicate five seams used to spell five ways, two of which disagreed on +/// the unknown-fingerprint case. +struct ConversationRenderEligibilityTests { + + private let tokenizer = GreedyTokenizer(pieces: [" "]) + + /// A key space carrying one image run — non-identity by construction, + /// built through the same fixture the builder suites use. + private func imageKeySpace() throws -> CacheKeySpace { + let conversation = HTTPPrefixCacheConversation( + systemPrompt: nil, + messages: [ + HTTPPrefixCacheMessage( + role: .user, content: "describe", + images: [HTTPPrefixCacheImage(data: Data([0x01]))] + ) + ] + ) + return try FakeChatMLTokenizer.keySpace(for: conversation, runLengths: [4]) + } /// An unknown fingerprint must BYPASS, never resolve under a synthetic /// shared key: the repeat path trusts (bytes, fingerprint) with no /// empirical arbiter behind it, so two models sharing a key could return /// each other's tokens. - @Test func unknownFingerprintBypassesEverySeam() { - #expect( - RenderTokenSource.forTextOnlyRequest( - hasMedia: false, producesFlatTextTokens: true, modelFingerprint: nil - ).cacheFingerprint == nil) - #expect( - RenderTokenSource.forIdentityKeySpace(.identity(), modelFingerprint: nil) - .cacheFingerprint == nil) + @Test func unknownFingerprintBypasses() { + #expect(makeRender(tokenizer, fingerprint: nil).cacheFingerprint == nil) } @Test func mediaAndNonFlatTokenModelsBypass() { + #expect(makeRender(tokenizer, hasMedia: true, fingerprint: "m").cacheFingerprint == nil) #expect( - RenderTokenSource.forTextOnlyRequest( - hasMedia: true, producesFlatTextTokens: true, modelFingerprint: "m" - ).cacheFingerprint == nil) - #expect( - RenderTokenSource.forTextOnlyRequest( - hasMedia: false, producesFlatTextTokens: false, modelFingerprint: "m" - ).cacheFingerprint == nil) + makeRender(tokenizer, producesFlatTextTokens: false, fingerprint: "m") + .cacheFingerprint == nil) } @Test func eligibleTextOnlyRequestCarriesTheFingerprint() { - #expect( - RenderTokenSource.forTextOnlyRequest( - hasMedia: false, producesFlatTextTokens: true, modelFingerprint: "m" - ).cacheFingerprint == "m") - #expect( - RenderTokenSource.forIdentityKeySpace(.identity(), modelFingerprint: "m") - .cacheFingerprint == "m") - } - - /// The plumbed base render travels with the eligibility decision and does - /// not alter it. - @Test func baseRenderTokensRideAlongWithoutChangingEligibility() { - let source = RenderTokenSource.forIdentityKeySpace(.identity(), modelFingerprint: "m") - .withBaseRenderTokens([1, 2, 3]) - #expect(source.cacheFingerprint == "m") - #expect(source.baseRenderTokens == [1, 2, 3]) - #expect(RenderTokenSource.uncached.cacheFingerprint == nil) - #expect(RenderTokenSource.uncached.baseRenderTokens == nil) + #expect(makeRender(tokenizer, fingerprint: "m").cacheFingerprint == "m") + } + + /// Sealing re-checks eligibility against the settled key space: identity + /// keeps the fingerprint, an image-bearing space clears it (placeholder + /// runs need the real token list, so those requests always render). + @Test func sealingKeepsTheFingerprintOnlyForAnIdentityKeySpace() throws { + let render = makeRender(tokenizer, fingerprint: "m") + #expect(render.sealed(for: .identity()).cacheFingerprint == "m") + #expect(try render.sealed(for: imageKeySpace()).cacheFingerprint == nil) + } + + /// The C31 plumbed base render travels with the eligibility decision and + /// does not alter it. + @Test func carriedBaseRenderRidesAlongWithoutChangingEligibility() { + let render = makeRender(tokenizer, fingerprint: "m").carryingBaseRender([1, 2, 3]) + #expect(render.cacheFingerprint == "m") + #expect(render.baseRenderTokens == [1, 2, 3]) + #expect(makeRender(tokenizer, fingerprint: nil).baseRenderTokens == nil) } } diff --git a/tesseractTests/ServerCompletionDrainTests.swift b/tesseractTests/ServerCompletionDrainTests.swift index 680316a7..8d27aa08 100644 --- a/tesseractTests/ServerCompletionDrainTests.swift +++ b/tesseractTests/ServerCompletionDrainTests.swift @@ -216,8 +216,7 @@ struct ServerCompletionDrainTests { let stored = turn1.appendingAssistant(.assistant(content: "OK")) let seed = SpeculativeCanonicalPrefill.makeSeed( storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, + render: ConversationRender.uncached(tokenizer: tokenizer), keySpace: .identity(keyPath: []), partitionKey: CachePartitionKey( modelID: "toy/model", kvBits: nil, kvGroupSize: 64 diff --git a/tesseractTests/SpeculativePrefillPreemptionTests.swift b/tesseractTests/SpeculativePrefillPreemptionTests.swift index 3701aadf..dcbe8d20 100644 --- a/tesseractTests/SpeculativePrefillPreemptionTests.swift +++ b/tesseractTests/SpeculativePrefillPreemptionTests.swift @@ -29,10 +29,8 @@ import Testing // The pass's own probe machinery computes the future shared path. let probed = try LeafAdmissionBuilder.futureSharedPrefix( storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, keySpace: .identity(keyPath: []), - renderContext: .canonical + render: ConversationRender.uncached(tokenizer: tokenizer) ) let futurePrefix = try #require(try probed?.get()) let admitPath = try #require( @@ -90,8 +88,7 @@ import Testing let seed = SpeculativeCanonicalPrefill.makeSeed( storedConversation: stored, - toolSpecs: nil, - tokenizer: tokenizer, + render: ConversationRender.uncached(tokenizer: tokenizer), keySpace: .identity(keyPath: []), partitionKey: partitionKey, prefillStepSize: 1024,