diff --git a/console/src/components/call-renderers/openai-chat.test.tsx b/console/src/components/call-renderers/openai-chat.test.tsx new file mode 100644 index 00000000..0150944a --- /dev/null +++ b/console/src/components/call-renderers/openai-chat.test.tsx @@ -0,0 +1,240 @@ +import { describe, expect, it } from "bun:test" +import { createElement } from "react" +import { renderToStaticMarkup } from "react-dom/server" +import { FinishBadge } from "../ui/finish-badge" +import { SummaryCards } from "../llm-call-detail/summary-cards" +import { OpenAiChatCallView, OpenAiChatOutputBlocks } from "./openai-chat" +import { parseOpenAiChatCall } from "../../lib/wire-apis/openai-chat" +import type { LlmCallDetail } from "../../types/api" + +function detail(overrides: Partial = {}): LlmCallDetail { + return { + id: "sample-call", + source_id: "sample-source", + request_time: 0, + response_time: 1, + complete_time: 2, + wire_api: "openai-chat", + model: "sample-model", + api_type: "chat", + is_stream: true, + request_path: "/v1/chat/completions", + status_code: 200, + finish_reason: null, + input_tokens: null, + output_tokens: null, + total_tokens: null, + ttft_ms: 1, + e2e_latency_ms: 2, + response_id: null, + client_ip: "", + client_port: 0, + server_ip: "", + server_port: 0, + request_body: null, + response_body: null, + request_headers: null, + response_headers: null, + is_agent_request: false, + tool_surface: null, + agent_topology: null, + tool_call_count: 0, + tool_names: [], + process: null, + ...overrides, + } +} + +function renderChat(responseBody: string | null): string { + return renderToStaticMarkup(createElement(OpenAiChatCallView, { + requestBody: null, + responseBody, + hasRequestBody: false, + })) +} + +function body(message: unknown, finishReason: string | null = null): string { + return JSON.stringify({ choices: [{ index: 0, message, finish_reason: finishReason }] }) +} + +describe("finish evidence display", () => { + it("visibly labels streaming missing finish without guessing an error", () => { + const markup = renderToStaticMarkup(createElement(FinishBadge, { reason: null, isStream: true, statusCode: 200 })) + expect(markup).toContain("Incomplete") + expect(markup).not.toContain("Stream error") + expect(markup).not.toContain("bg-red-") + }) + + it("preserves raw provider finish values", () => { + const markup = renderToStaticMarkup(createElement(FinishBadge, { reason: "provider_terminal", isStream: true, statusCode: 200 })) + expect(markup).toContain("provider_terminal") + expect(markup).not.toContain("Incomplete") + }) + + for (const props of [ + { reason: null }, + { reason: null, isStream: false, statusCode: 200 }, + { reason: null, isStream: true, statusCode: 429 }, + ]) { + it(`keeps missing finish neutral outside an unfinished HTTP-success stream ${JSON.stringify(props)}`, () => { + const markup = renderToStaticMarkup(createElement(FinishBadge, props)) + expect(markup).toContain("—") + expect(markup).not.toContain("Incomplete") + expect(markup).not.toContain("Stream error") + }) + } + + it("marks HTTP 200 without finish as incomplete in the detail summary", () => { + const markup = renderToStaticMarkup(createElement(SummaryCards, { detail: detail() })) + expect(markup).toContain("200") + expect(markup).toContain("Incomplete") + expect(markup).not.toContain("Stream error") + }) + + it("shows the full parsed stream error alongside preserved HTTP status", () => { + const response_body = JSON.stringify({ error: { + message: "Synthetic stream failure", + type: "sample_error", + code: "sample_overload", + extra: { detail: "preserved nested value" }, + } }) + const markup = renderToStaticMarkup(createElement(SummaryCards, { detail: detail({ response_body }) })) + expect(markup).toContain("200") + expect(markup).toContain("Stream error") + expect(markup).toContain('role="alert"') + expect(markup).toContain("Synthetic stream failure") + expect(markup).toContain("sample_error") + expect(markup).toContain("sample_overload") + expect(markup).toContain("preserved nested value") + }) + + it("uses shared stream error display for Responses details", () => { + const markup = renderToStaticMarkup(createElement(SummaryCards, { detail: detail({ + wire_api: "openai-responses", + response_body: '{"error":{"message":"Synthetic response failure","code":"sample_error"}}', + }) })) + expect(markup).toContain("Stream error") + expect(markup).toContain("Synthetic response failure") + }) + + it("keeps raw stop visible even when a stream error is also captured", () => { + const markup = renderToStaticMarkup(createElement(SummaryCards, { detail: detail({ + finish_reason: "stop", + response_body: '{"error":{"message":"Synthetic late failure"}}', + }) })) + expect(markup).toContain("stop") + expect(markup).toContain("Stream error") + expect(markup).toContain("Synthetic late failure") + }) + + for (const overrides of [ + { is_stream: false }, + { status_code: 400 }, + ]) { + it(`does not relabel existing HTTP/non-streaming errors ${JSON.stringify(overrides)}`, () => { + const markup = renderToStaticMarkup(createElement(SummaryCards, { detail: detail({ + response_body: '{"error":{"message":"Synthetic request failure"}}', + ...overrides, + }) })) + expect(markup).not.toContain("Stream error") + expect(markup).not.toContain("Incomplete") + }) + } +}) + +describe("Chat effective output display", () => { + for (const responseBody of [null, "", '{"choices":', "null", "[]"]) { + it(`does not infer no valid output from an unavailable or unparsed full-view body ${String(responseBody)}`, () => { + const markup = renderChat(responseBody) + expect(markup).not.toContain("No valid output") + expect(markup).toContain("Input") + expect(markup).toContain("Output") + }) + } + + for (const responseBody of [null, '{"choices":', '{"choices":[],"usage":{"completion_tokens":3}}']) { + it(`keeps output-only zero choices neutral without raw body evidence ${String(responseBody)}`, () => { + const response = parseOpenAiChatCall(null, responseBody).response + const markup = renderToStaticMarkup(createElement(OpenAiChatOutputBlocks, { response })) + expect(markup).not.toContain("No valid output") + expect(markup).toContain("No response content.") + }) + } + + for (const message of [ + { role: "assistant" }, + { role: "assistant", content: "" }, + { role: "assistant", content: null }, + { role: "assistant", content: [] }, + ]) { + it(`shows no valid output for a synthetic shell ${JSON.stringify(message)}`, () => { + const markup = renderChat(body(message)) + expect(markup).toContain("No valid output") + }) + } + + it("shows no valid output for a usage-only response", () => { + expect(renderChat('{"choices":[],"usage":{"completion_tokens":3}}')).toContain("No valid output") + }) + + it("does not mistake normal stop plus empty content for a stream error", () => { + const response_body = body({ role: "assistant", content: "" }, "stop") + const markup = renderToStaticMarkup(createElement("div", null, + createElement(SummaryCards, { detail: detail({ finish_reason: "stop", response_body }) }), + createElement(OpenAiChatCallView, { requestBody: null, responseBody: response_body, hasRequestBody: false }), + )) + expect(markup).toContain("No valid output") + expect(markup).toContain("stop") + expect(markup).not.toContain("Stream error") + expect(markup).not.toContain("Incomplete") + }) + + it("retains partial text and tools when a stream error is present", () => { + const response_body = JSON.stringify({ + choices: [{ index: 0, message: { + role: "assistant", + content: "Synthetic partial answer", + tool_calls: [{ id: "sample-tool-call", type: "function", function: { name: "sample_tool", arguments: '{"partial":' } }], + }, finish_reason: null }], + error: { message: "Synthetic stream failure", extra: { detail: "complete error detail" } }, + }) + const markup = renderToStaticMarkup(createElement("div", null, + createElement(SummaryCards, { detail: detail({ response_body }) }), + createElement(OpenAiChatCallView, { requestBody: null, responseBody: response_body, hasRequestBody: false }), + )) + expect(markup).toContain("Stream error") + expect(markup).toContain("complete error detail") + expect(markup).toContain("Synthetic partial answer") + expect(markup).toContain("sample_tool") + expect(markup).toContain("partial") + expect(markup).not.toContain("No valid output") + }) + + for (const message of [ + { role: "assistant", content: "Synthetic complete answer" }, + { role: "assistant", reasoning_content: "Synthetic reasoning" }, + { role: "assistant", tool_calls: [{ id: "sample-tool-call", type: "function", function: { name: "sample_tool", arguments: "{}" } }] }, + ]) { + it(`keeps actual output free of empty-output warnings ${JSON.stringify(message)}`, () => { + const markup = renderChat(body(message, "stop")) + expect(markup).not.toContain("No valid output") + expect(markup).not.toContain("Stream error") + }) + } + + it("renders reasoning alias output instead of calling it empty", () => { + const response_body = body({ role: "assistant", reasoning: "Synthetic reasoning alias" }, "stop") + const markup = renderChat(response_body) + expect(markup).toContain("Synthetic reasoning alias") + expect(markup).not.toContain("No valid output") + const response = parseOpenAiChatCall(null, response_body).response + const outputMarkup = renderToStaticMarkup(createElement(OpenAiChatOutputBlocks, { response })) + expect(outputMarkup).toContain("Synthetic reasoning alias") + expect(outputMarkup).not.toContain("No valid output") + }) + + it("uses the same empty-output check in output-only cards", () => { + const response = parseOpenAiChatCall(null, body({ role: "assistant", content: "" }, "stop")).response + expect(renderToStaticMarkup(createElement(OpenAiChatOutputBlocks, { response }))).toContain("No valid output") + }) +}) diff --git a/console/src/components/call-renderers/openai-chat.tsx b/console/src/components/call-renderers/openai-chat.tsx index 4a090d2d..9d101fe5 100644 --- a/console/src/components/call-renderers/openai-chat.tsx +++ b/console/src/components/call-renderers/openai-chat.tsx @@ -3,6 +3,7 @@ import { ChevronRight, ChevronDown, FileJson, Activity } from "lucide-react" import { cn } from "@/lib/utils" import { Markdown } from "@/components/ui/markdown" import { parseOpenAiChatCall } from "@/lib/wire-apis/openai-chat" +import { deriveCallOutcome, hasOpenAiChatOutput } from "@/lib/call-outcome" import type { OpenAiChatChoice, OpenAiChatMessage, @@ -519,12 +520,19 @@ function LogprobsPanel({ choice }: { choice: OpenAiChatChoice }) { ) } +function EmptyOutputNotice() { + return ( +
+ No valid output. +
+ ) +} + function ResponseCard({ response, ctx }: { response: OpenAiChatResponse; ctx?: OutputCtx }) { - if (response.choices.length === 0) { - return
No choices in response.
- } + if (response.choices.length === 0) return return (
+ {!hasOpenAiChatOutput(response) && } {response.choices.map((c, i) => ( ))} @@ -622,6 +630,13 @@ export function OpenAiChatCallView({ hasRequestBody, }: OpenAiChatCallViewProps) { const call = useMemo(() => parseOpenAiChatCall(requestBody, responseBody), [requestBody, responseBody]) + const outputState = useMemo(() => deriveCallOutcome({ + is_stream: false, + status_code: null, + finish_reason: null, + wire_api: "openai-chat", + response_body: responseBody, + }).outputState, [responseBody]) return ( <>
@@ -643,7 +658,11 @@ export function OpenAiChatCallView({
Output
- + {outputState === "unknown" ? ( +
No response content.
+ ) : ( + + )}
) @@ -655,6 +674,7 @@ export function OpenAiChatOutputBlocks({ response, ctx }: { response: OpenAiChat } return (
+ {!hasOpenAiChatOutput(response) && } {response.choices.map((c, i) => )}
) diff --git a/console/src/components/llm-call-detail/summary-cards.tsx b/console/src/components/llm-call-detail/summary-cards.tsx index 5665f1b0..40f04f23 100644 --- a/console/src/components/llm-call-detail/summary-cards.tsx +++ b/console/src/components/llm-call-detail/summary-cards.tsx @@ -1,6 +1,7 @@ import { StatusBadge } from "@/components/ui/status-badge" import { FinishBadge } from "@/components/ui/finish-badge" import { formatMs, formatNumber } from "@/lib/format" +import { deriveCallOutcome } from "@/lib/call-outcome" import type { LlmCallDetail } from "@/types/api" function SummaryCard({ label, children }: { label: string; children: React.ReactNode }) { @@ -17,6 +18,7 @@ interface Props { } export function SummaryCards({ detail }: Props) { + const outcome = deriveCallOutcome(detail) return (
@@ -28,7 +30,7 @@ export function SummaryCards({ detail }: Props) {
- +
@@ -75,6 +77,14 @@ export function SummaryCards({ detail }: Props) { {formatNumber(detail.total_tokens)}
+ {outcome.streamState === "stream-error" && ( +
+
Stream error
+
+            {JSON.stringify(outcome.error, null, 2)}
+          
+
+ )}
) } diff --git a/console/src/components/ui/finish-badge.tsx b/console/src/components/ui/finish-badge.tsx index ab1c7621..15452a2b 100644 --- a/console/src/components/ui/finish-badge.tsx +++ b/console/src/components/ui/finish-badge.tsx @@ -1,17 +1,27 @@ import { cn } from "@/lib/utils" import { finishTone, TONE_CLASS } from "@/lib/finish-tone" +import { deriveCallOutcome } from "@/lib/call-outcome" -export function FinishBadge({ reason }: { reason: string | null }) { - if (!reason) return — - const tone = finishTone(reason) +interface Props { + reason: string | null + isStream?: boolean + statusCode?: number | null +} + +export function FinishBadge({ reason, isStream = false, statusCode = null }: Props) { + const outcome = deriveCallOutcome({ is_stream: isStream, status_code: statusCode, finish_reason: reason }) + if (!reason && outcome.streamState !== "incomplete") return — + const incomplete = outcome.streamState === "incomplete" + const tone = incomplete ? "warn" : finishTone(reason) return ( - {reason} + {incomplete ? "Incomplete" : reason} ) } diff --git a/console/src/lib/call-outcome.test.ts b/console/src/lib/call-outcome.test.ts new file mode 100644 index 00000000..919503ee --- /dev/null +++ b/console/src/lib/call-outcome.test.ts @@ -0,0 +1,142 @@ +import { describe, expect, it } from "bun:test" +import { deriveCallOutcome, hasOpenAiChatOutput, type CallOutcome, type CallOutcomeInput } from "./call-outcome" +import { parseOpenAiChatCall } from "./wire-apis/openai-chat" + +function input(overrides: Partial = {}): CallOutcomeInput { + return { + is_stream: true, + status_code: 200, + finish_reason: null, + wire_api: "openai-chat", + ...overrides, + } +} + +function chatBody(message: unknown, finishReason: string | null = null): string { + return JSON.stringify({ choices: [{ index: 0, message, finish_reason: finishReason }] }) +} + +describe("deriveCallOutcome stream evidence", () => { + const cases: Array<{ name: string; given: Partial; state: CallOutcome["streamState"] }> = [ + { name: "HTTP 200 without a finish reason is incomplete", given: {}, state: "incomplete" }, + { name: "missing HTTP status does not establish stream completion", given: { status_code: null }, state: "incomplete" }, + { name: "stop is a finished stream", given: { finish_reason: "stop" }, state: "finished" }, + { name: "tool_calls retains its provider finish reason", given: { finish_reason: "tool_calls" }, state: "finished" }, + { name: "unknown finish values are not rewritten", given: { finish_reason: "provider_terminal" }, state: "finished" }, + { name: "non-streaming missing finish keeps its existing treatment", given: { is_stream: false }, state: "not-streaming" }, + { name: "HTTP 400 keeps its HTTP error treatment", given: { status_code: 400 }, state: "http-error" }, + { name: "HTTP 503 with a finish reason is still an HTTP error", given: { status_code: 503, finish_reason: "stop" }, state: "http-error" }, + { name: "non-streaming HTTP 429 remains an HTTP error", given: { status_code: 429, is_stream: false }, state: "http-error" }, + { name: "captured top-level error establishes a stream error", given: { response_body: '{"error":{"message":"Synthetic stream failure"}}' }, state: "stream-error" }, + { name: "captured error takes precedence over a finish reason", given: { finish_reason: "stop", response_body: '{"error":"Synthetic stream failure"}' }, state: "stream-error" }, + { name: "non-streaming response error is not called a stream error", given: { is_stream: false, response_body: '{"error":{"message":"Synthetic request failure"}}' }, state: "not-streaming" }, + { name: "null error is not evidence of stream failure", given: { finish_reason: "stop", response_body: '{"error":null}' }, state: "finished" }, + { name: "malformed JSON does not invent a stream error", given: { response_body: '{"error":' }, state: "incomplete" }, + { name: "nested content error is not a provider error", given: { finish_reason: "stop", response_body: chatBody({ role: "assistant", content: '{"error":"sample"}' }, "stop") }, state: "finished" }, + ] + + for (const { name, given, state } of cases) { + it(name, () => { + const result = deriveCallOutcome(input(given)) + expect(result.streamState).toBe(state) + expect(result.finishReason).toBe(given.finish_reason ?? null) + }) + } + + for (const error of [ + { message: "Synthetic stream failure", type: "sample_error", code: "sample_overload", extra: { retryable: true } }, + "Synthetic stream failure", + ["Synthetic stream failure", { detail: "retained" }], + 0, + false, + "", + ]) { + it(`retains the complete parsed error value ${JSON.stringify(error)}`, () => { + const response_body = JSON.stringify({ error }) + const given = input({ response_body }) + const result = deriveCallOutcome(given) + expect(result.error).toEqual(error) + expect(result.streamState).toBe("stream-error") + expect(given.response_body).toBe(response_body) + expect(given.finish_reason).toBeNull() + }) + } +}) + +describe("Chat effective output", () => { + const cases: Array<{ name: string; message: unknown; content: boolean }> = [ + { name: "role-only assistant shell is empty", message: { role: "assistant" }, content: false }, + { name: "null content shell is empty", message: { role: "assistant", content: null }, content: false }, + { name: "empty content shell is empty", message: { role: "assistant", content: "" }, content: false }, + { name: "whitespace-only content is empty", message: { role: "assistant", content: " \n\t" }, content: false }, + { name: "empty content parts are empty", message: { role: "assistant", content: [] }, content: false }, + { name: "empty text part is empty", message: { role: "assistant", content: [{ type: "text", text: "" }] }, content: false }, + { name: "empty reasoning and tools do not establish output", message: { role: "assistant", content: "", reasoning_content: "", tool_calls: [] }, content: false }, + { name: "empty tool shell is empty", message: { role: "assistant", tool_calls: [{}] }, content: false }, + { name: "partial text establishes output", message: { role: "assistant", content: "Synthetic partial answer" }, content: true }, + { name: "reasoning-only response establishes output", message: { role: "assistant", reasoning_content: "Synthetic reasoning" }, content: true }, + { name: "reasoning alias establishes output", message: { role: "assistant", reasoning: "Synthetic reasoning alias" }, content: true }, + { name: "tool-only response establishes output", message: { role: "assistant", tool_calls: [{ id: "sample-call", type: "function", function: { name: "sample_tool", arguments: "{}" } }] }, content: true }, + { name: "partial tool arguments establish output", message: { role: "assistant", tool_calls: [{ function: { arguments: '{"partial":' } }] }, content: true }, + { name: "refusal establishes output", message: { role: "assistant", refusal: "Synthetic refusal" }, content: true }, + { name: "text content part establishes output", message: { role: "assistant", content: [{ type: "text", text: "Synthetic answer" }] }, content: true }, + { name: "image content establishes output", message: { role: "assistant", content: [{ type: "image_url", image_url: { url: "data:image/png;base64,c2FtcGxl" } }] }, content: true }, + ] + + for (const { name, message, content } of cases) { + it(name, () => { + const response_body = chatBody(message, "stop") + const response = parseOpenAiChatCall(null, response_body).response + expect(hasOpenAiChatOutput(response)).toBe(content) + const outcome = deriveCallOutcome(input({ response_body, finish_reason: "stop" })) + expect(outcome.outputState).toBe(content ? "content" : "empty") + expect(outcome.streamState).toBe("finished") + expect(outcome.error).toBeNull() + }) + } + + it("usage-only synthetic JSON has no effective output", () => { + const result = deriveCallOutcome(input({ response_body: '{"choices":[],"usage":{"completion_tokens":8}}' })) + expect(result.outputState).toBe("empty") + expect(result.streamState).toBe("incomplete") + }) + + it("checks all choices rather than just the first", () => { + const response_body = JSON.stringify({ choices: [ + { index: 0, message: { role: "assistant", content: "" }, finish_reason: "stop" }, + { index: 1, message: { role: "assistant", reasoning_content: "Synthetic reasoning" }, finish_reason: "stop" }, + ] }) + expect(deriveCallOutcome(input({ response_body, finish_reason: "stop" })).outputState).toBe("content") + }) + + it("retains partial output alongside stream errors", () => { + const response_body = JSON.stringify({ + choices: [{ index: 0, message: { role: "assistant", content: "Synthetic partial answer" }, finish_reason: null }], + error: { message: "Synthetic stream failure" }, + }) + expect(deriveCallOutcome(input({ response_body }))).toEqual({ + streamState: "stream-error", + finishReason: null, + error: { message: "Synthetic stream failure" }, + outputState: "content", + }) + }) + + for (const response_body of [undefined, null, "", "not JSON", "null", "[]"]) { + it(`does not infer empty output from unavailable or unparsed body ${String(response_body)}`, () => { + expect(deriveCallOutcome(input({ response_body })).outputState).toBe("unknown") + }) + } + + it("does not apply Chat empty-output inference to other wire APIs", () => { + const result = deriveCallOutcome(input({ wire_api: "openai-responses", finish_reason: "completed", response_body: '{"output":[{"type":"message"}]}' })) + expect(result.outputState).toBe("unknown") + expect(result.streamState).toBe("finished") + }) + + it("uses the shared top-level error contract for Responses details", () => { + const result = deriveCallOutcome(input({ wire_api: "openai-responses", response_body: '{"error":{"code":"sample_error","message":"Synthetic response failure"}}' })) + expect(result.streamState).toBe("stream-error") + expect(result.error).toEqual({ code: "sample_error", message: "Synthetic response failure" }) + }) +}) diff --git a/console/src/lib/call-outcome.ts b/console/src/lib/call-outcome.ts new file mode 100644 index 00000000..eaa2f9fb --- /dev/null +++ b/console/src/lib/call-outcome.ts @@ -0,0 +1,61 @@ +import { parseOpenAiChatCall } from "./wire-apis/openai-chat" +import type { OpenAiChatPart, OpenAiChatResponse } from "./wire-apis/openai-chat/types" +import { asObject, parseJsonOrNull } from "./wire-apis/shared" + +export interface CallOutcomeInput { + is_stream: boolean + status_code: number | null + finish_reason: string | null + wire_api?: string + response_body?: string | null +} + +export interface CallOutcome { + streamState: "not-streaming" | "http-error" | "stream-error" | "incomplete" | "finished" + finishReason: string | null + error: unknown | null + outputState: "unknown" | "empty" | "content" +} + +export function deriveCallOutcome(input: CallOutcomeInput): CallOutcome { + const body = asObject(parseJsonOrNull(input.response_body)) + const error = body?.error ?? null + const outputState = input.wire_api === "openai-chat" && body + ? hasOpenAiChatOutput(parseOpenAiChatCall(null, input.response_body).response) ? "content" : "empty" + : "unknown" + + let streamState: CallOutcome["streamState"] + if ((input.status_code ?? 0) >= 400) streamState = "http-error" + else if (!input.is_stream) streamState = "not-streaming" + else if (error !== null) streamState = "stream-error" + else if (!input.finish_reason) streamState = "incomplete" + else streamState = "finished" + + return { streamState, finishReason: input.finish_reason, error, outputState } +} + +function hasText(value: string | null | undefined): boolean { + return typeof value === "string" && value.trim().length > 0 +} + +function hasContentPart(part: OpenAiChatPart): boolean { + switch (part.type) { + case "text": return hasText(part.text) + case "image_url": return hasText(part.image_url.url) + case "input_audio": return hasText(part.input_audio.data) + case "unknown": return part.raw != null + } +} + +export function hasOpenAiChatOutput(response: OpenAiChatResponse): boolean { + return response.choices.some(({ message }) => + (typeof message.content === "string" + ? hasText(message.content) + : message.content?.some(hasContentPart) === true) + || hasText(message.reasoning_content) + || hasText(message.refusal) + || message.tool_calls?.some((tool) => + hasText(tool.id) || hasText(tool.function.name) || hasText(tool.function.arguments), + ) === true, + ) +} diff --git a/console/src/lib/wire-apis/openai-chat/index.test.ts b/console/src/lib/wire-apis/openai-chat/index.test.ts index 049d63e1..bba144f4 100644 --- a/console/src/lib/wire-apis/openai-chat/index.test.ts +++ b/console/src/lib/wire-apis/openai-chat/index.test.ts @@ -105,6 +105,27 @@ describe("parseOpenAiChatCall — request", () => { }) describe("parseOpenAiChatCall — response", () => { + it("retains reasoning alias output for response display", () => { + const body = JSON.stringify({ choices: [{ + index: 0, + message: { role: "assistant", content: null, reasoning: "Synthetic reasoning alias" }, + finish_reason: "stop", + }] }) + const message = parseOpenAiChatCall(null, body).response.choices[0].message + expect(message.reasoning_content).toBe("Synthetic reasoning alias") + expect(body).toContain('"reasoning":"Synthetic reasoning alias"') + expect(body).not.toContain("reasoning_content") + }) + + it("keeps reasoning_content preferred when both reasoning spellings exist", () => { + const body = JSON.stringify({ choices: [{ + index: 0, + message: { role: "assistant", reasoning_content: "Primary synthetic reasoning", reasoning: "Fallback synthetic reasoning" }, + finish_reason: "stop", + }] }) + expect(parseOpenAiChatCall(null, body).response.choices[0].message.reasoning_content).toBe("Primary synthetic reasoning") + }) + it("text output: choices[0].message.content is a string", () => { const call = parseOpenAiChatCall(null, fx("openai_chat_output_text.json")) expect(call.response.choices).toHaveLength(1) diff --git a/console/src/lib/wire-apis/openai-chat/index.ts b/console/src/lib/wire-apis/openai-chat/index.ts index 0e0a3a38..98cd2649 100644 --- a/console/src/lib/wire-apis/openai-chat/index.ts +++ b/console/src/lib/wire-apis/openai-chat/index.ts @@ -289,7 +289,7 @@ function parseChoices(raw: unknown): OpenAiChatChoice[] { } const tc = parseToolCalls(get(msgRaw, "tool_calls")) if (tc.length > 0) message.tool_calls = tc - const reasoning = asString(get(msgRaw, "reasoning_content")) + const reasoning = asString(get(msgRaw, "reasoning_content")) ?? asString(get(msgRaw, "reasoning")) if (reasoning != null && reasoning.length > 0) message.reasoning_content = reasoning const refusal = asString(get(msgRaw, "refusal")) if (refusal != null) message.refusal = refusal diff --git a/console/src/pages/llm-calls.tsx b/console/src/pages/llm-calls.tsx index 2339105d..b1ef2ee0 100644 --- a/console/src/pages/llm-calls.tsx +++ b/console/src/pages/llm-calls.tsx @@ -94,7 +94,7 @@ function CellValue({ item, column }: { item: LlmCallListItem; column: SortKey }) ) case "finish_reason": - return + return case "ttft_ms": if (item.ttft_ms == null) { return — diff --git a/docs/configure.md b/docs/configure.md index 2196dfe7..f235be68 100644 --- a/docs/configure.md +++ b/docs/configure.md @@ -84,6 +84,12 @@ bpf_filter = "tcp port 8000" # see "BPF filters" below snaplen = 262144 # max bytes per packet (256 KiB default) ``` +Each live source requests a 64 MiB libpcap capture buffer to absorb short +packet bursts. The operating system determines the actual allocation. This +bounded per-source reserve does not replace downstream capacity planning; +sustained overload can still drop packets. The startup log reports the +requested buffer size, and capture counters report observed kernel drops. + #### `pcap-file` — replay from a file ```toml @@ -208,6 +214,83 @@ path = "data/heron.duckdb" The path is relative to the working directory. Parent directories are created automatically on first run. +For constrained hosts, optional resource settings apply to the shared database +instance and survive connection recovery: + +```toml +[storage.duckdb] +path = "data/heron.duckdb" +threads = 1 +memory_limit_mb = 768 +read_pool_size = 1 +allocator_background_threads = true +``` + +`allocator_background_threads` enables DuckDB's own allocator housekeeping where +supported. This can release unused resident pages after large writes without +waiting for another task on the same allocator arena. It does not replace the +memory budget or bound all allocations; the extra background work shares the +process CPU limit. Omit it to retain DuckDB's default, or set it to `false` to +explicitly disable it. Connection recovery preserves the configured value. + +Pairing maintenance requests a periodic checkpoint only after metadata updates +or while retrying failed maintenance. Unchanged scans do not checkpoint unrelated +body writes; shutdown still performs a final checkpoint. A checkpoint waits for +current batches on all four writers, then pauses new batches until it completes. +This avoids writer/checkpoint lock conflicts; it does not guarantee that a given +memory budget can handle the load. + +Omitting these keys preserves DuckDB's automatic thread/memory sizing and the +four-reader pool. The memory budget uses decimal MB and covers DuckDB-managed +memory, not every allocation in Heron. An overly small budget can fail writes; +monitor storage flush errors and capture drops. Set a process memory/CPU limit +through the service manager as well, and tune pipeline queues and batch size for +large bodies. CLI `-i` and `--pcap-file` replace pipeline definitions with defaults; +to retain these queue settings, define the source in the config instead. + +### Sequential journal ingestion (opt-in) + +```toml +[storage.duckdb] +path = "data/heron.duckdb" +journal = true + +[storage.retention] +enabled = false +``` + +Journal mode appends full captured bodies and headers to segmented files beside +`.journal`. Equal payload bytes share a reference while present in +a bounded recent-content cache. DuckDB stores small metadata and typed references; +call/HTTP details read the payload on demand. Legacy inline records remain readable. +Lists and lite turn views do not read payload files; token-estimation flags are +computed before externalizing the response. This changes storage, not the upstream +body-cap policy or SSE reconstruction behavior. + +A write acknowledgement means the payload and record files have been synced. +One independent index worker reads bounded metadata batches from disk. Each index +transaction commits its rows, payload references and journal cursor together; +failed indexing retries the same durable records, including after a restart. +There is no in-memory backlog proportional to the journal size. Shutdown waits +for indexing to reach the durable watermark before final pairing maintenance. +A failed append stops the supervised capture pipeline rather than dropping a +batch. Disk capacity still bounds ingestion; monitor free space and the logged +`durable`/`indexed` watermarks and index errors. + +Files rotate at a 64 MiB target; an individual larger payload is kept intact. +Metadata batches target 256 KiB with a 16 MiB format ceiling per record/batch; +wide and finish metric rows are committed together. Recovery repairs only an +incomplete final frame; a complete checksum mismatch or non-final damaged segment +is an error. Keep the database and its journal directory together when moving or +removing a dataset. Disabling journal mode does not convert existing external +payloads back into inline bodies or erase their files. + +Automatic row retention is rejected for journal-owned datasets, including after +journal mode is disabled. It cannot reclaim a shared segment by deleting only +one database row. Manage the complete dataset's lifetime explicitly; segment +compaction and automatic journal retention are not implemented. The default +`journal = false` retains the existing inline backend and retention behavior. + ### ClickHouse-specific ```toml diff --git a/docs/design/04-turn.md b/docs/design/04-turn.md index 56b24286..8f467600 100644 --- a/docs/design/04-turn.md +++ b/docs/design/04-turn.md @@ -27,6 +27,26 @@ This design is implemented by the `ts-turn` crate (see `server/ts-turn/`). expiry the buffer is partitioned at each terminal and one `AgentTurn` is emitted per partition. This tolerates arbitrary intra-shard arrival order (fan-in jitter, multi-connection sessions, parallel sub-agents). +- **Buffered ownership:** the turn tracker converts each incoming agent call to + a private metadata summary. It retains the call id, timing, token counts, + classification, process-attribution presence, and at most 500 Unicode + characters plus an ellipsis for each preview. Full request/response bodies + and headers remain on the independent storage path; pending turns do not + keep the original `Arc` alive after ingestion. +- **Active snapshot ownership:** a published `Trace` belongs to the partition + it represents. Completion, discard, idle, drain and tracker exit retire that + partition's snapshot, including partitions that emit no completed record. + Finalizing a head immediately refreshes any valid tail; a tracker sharing a + registry removes only its own published IDs. A new ID is reserved against the + earliest represented main-agent call carrying user-start or PID eligibility, + so an earlier ineligible prefix cannot consume a valid tail's identity. Existing + reservations keep their original ownership. +- **Ordered append work:** the ordinary ordered path updates the existing + snapshot incrementally, with insertion-ordered unique collections. Pending + counts and terminal/grace/idle indexes avoid rescanning all calls or sessions + on every ingest. Reordering or a partition-boundary change rebuilds only the + affected snapshot; persisted turns retain the existing request-time and + same-timestamp insertion order. - Turn boundaries: profile-defined terminal predicate (`is_turn_terminal` / definitive `finish_reason`) OR idle timeout (default 600 s, packet-time driven). Partitions without `is_user_turn_start = Some(true)` are dropped diff --git a/docs/design/06-storage.md b/docs/design/06-storage.md index d40ca795..58109185 100644 --- a/docs/design/06-storage.md +++ b/docs/design/06-storage.md @@ -33,6 +33,22 @@ LlmMetric ──┘ See [schema.md](07-schema.md) for data schema and backend adaptation notes, and [aglake.md](10-aglake.md) for the one backend that is not a SQL database. +## ClickHouse Read Paths + +ClickHouse persists a nullable token-estimation summary for span lists. The shared Rust helper defines the value, including malformed or non-numeric usage fields. New writes supply the summary; legacy `NULL` values are backfilled in paced, bounded batches with durable completion markers. Maintenance walks physical key pages and hydrates only unknowns, so searching for sparse unknown rows does not scan all completed history in one step. A restart may revisit completed key pages before reaching remaining unknowns. A list page fetches bodies only for legacy unknowns that need compatibility evaluation. Detail and export reads retain complete request and response bodies. + +Topology reads stream minimal trace fields and each trace's first span ID, then resolve endpoints in bounded batches within the same microsecond time window. Compact endpoint frequencies span batch boundaries: a proxy group with two inbound turns and three outbound turns still contributes six pair edges. A resource-budget failure returns an explicit error instead of a partial graph. Read paths remain JOIN-free and use ID tie-breaks for deterministic pagination. + +## ClickHouse Pairing Maintenance + +The backend owns its paged pairing sweep. A narrow time-ordered candidate table mirrors every trace version through a materialized view; latest-version selection precedes the unpaired-role filter. The view is installed before backfill. A new initialization job freezes an upper bound that also covers pre-view rows with future event timestamps; ordinary forward windows reuse readiness. Initialization records fixed bounds and progress, and rechecks coverage when the lower window bound widens or index objects are rebuilt. Authoritative traces retain complete metadata and child IDs. + +Each sweep scans a fixed rolling window with timestamp and ID cursors. Open fingerprint clusters span page boundaries until the existing adjacency rule proves they are complete. The same classifier assigns groups; explicit state and plan budgets reject oversized cohorts without truncation. + +Before applying a group's metadata, the backend persists its original member IDs and exact patches. Pending plans replay before new discovery, independently of the current role or window. Batched writes read fresh authoritative rows, preserve unrelated metadata, and use checked increasing versions. Missing rows stay deleted. Completed groups remain excluded from new discovery, preserving the existing late-arrival behavior. + +Initialization, discovery, repair and retention share a backend-local gate. Trace retention removes expired candidate versions by the same end-time cutoff before deleting authoritative rows; pending plans always re-read the surviving traces. Initialization and object recovery may scan authoritative history once. Recurring discovery uses the candidate time key, but server granules, index fragmentation and a single indivisible row can still affect physical I/O and memory beyond the application-level page and aggregation budgets. + ## File Structure ``` diff --git a/docs/design/07-schema.md b/docs/design/07-schema.md index c9ac634a..07db63d0 100644 --- a/docs/design/07-schema.md +++ b/docs/design/07-schema.md @@ -77,6 +77,7 @@ Indexes: - **Performance metrics in requests table**: `ttft_ms` and `e2e_latency_ms` are computed at write time for fast single-record queries. Per-call Token Throughput can be derived: `output_tokens / (complete_time - response_time)` (tokens/s). - **Full body storage**: `request_body` and `response_body` store complete JSON. For streaming responses, `response_body` contains the concatenated final content. +- **ClickHouse token-estimate summary**: `spans.tokens_estimated` is an additive `Nullable(Bool)` projection computed with the shared Rust token-estimation helper. New writes always set it; `NULL` marks legacy rows awaiting a paced, resumable backfill. List queries select the summary without `response_body` and hydrate only legacy unknowns when needed. The complete body columns remain available to detail and export reads. - **Headers storage**: `request_headers` and `response_headers` store complete HTTP headers as JSON arrays of `[key, value]` pairs, preserving order and allowing duplicate keys. Rate limit info, request IDs, processing time, etc. can be queried from stored headers without top-level extraction. - **`response_id`**: Wire API's response/message ID (e.g., OpenAI `chatcmpl-xxx`, Anthropic `msg_xxx`). Promoted to top-level for fast cross-referencing with vendor logs. @@ -132,7 +133,13 @@ Indexes: - **`status`** (`VARCHAR NOT NULL`) — Two values only: `complete` (a wire-level terminal landed before finalize) or `incomplete` (idle timeout, pcap EOF, server shutdown, or connection RST mid-stream). The wire-level reason — `end_turn`, `max_tokens`, `refusal`, etc. — lives in `final_finish_reason`. Older databases written when the column carried `length` / `failed` / `cancelled` are upgraded in place on init: `length → complete`, `failed`/`cancelled → incomplete`. The wire reason for those legacy rows is unrecoverable. - **`final_finish_reason`** (`VARCHAR`, nullable) — Raw `finish_reason` of the call that closed this turn. Same vocabulary as `spans.finish_reason` (per `wire_api`); same migration caveat for rows pre-dating the raw-string refactor. -- **`span_ids`** carries the ordered child UUIDs inline so detail reads can issue a single `SELECT ... FROM spans WHERE id IN (?, ?, ...)` follow-up. See `query_trace_spans` in `h-storage-duckdb/src/turns.rs` for the canonical pattern. Storing this list inline is the project's chosen alternative to a relational JOIN. +- **`span_ids`** carries the ordered child UUIDs inline so detail reads can issue a single `SELECT ... FROM spans WHERE id IN (?, ?, ...)` follow-up. `start_time` is the first child's exact request timestamp; child IDs retain request-time order with stable same-time ties. ClickHouse topology uses that timestamp together with the first child ID for time-pruned endpoint lookup. See `query_trace_spans` in `h-storage-duckdb/src/turns.rs` for the canonical pattern. Storing this list inline is the project's chosen alternative to a relational JOIN. + +### ClickHouse pairing projections + +`trace_pair_candidates` is a narrow `ReplacingMergeTree(_version)` keyed by `(start_time, turn_id)`. The materialized view copies every inserted trace version, including its current proxy role and unchanged source version. Reads resolve the latest version before filtering the role, so unmerged paired versions cannot expose an older unpaired row. `start_time` and `turn_id` are immutable for a trace. + +`trace_pair_index_state` records initialization object identities, fixed time bounds and acknowledged backfill progress. `trace_pair_repairs` records each unfinished group's original member IDs, time context and exact metadata patches before any member update. Both are versioned internal maintenance tables; complete authoritative rows remain in `traces`. End-time retention removes expired candidate versions before authoritative traces under the same maintenance gate. --- diff --git a/docs/install.md b/docs/install.md index f7b06e85..b04a19c0 100644 --- a/docs/install.md +++ b/docs/install.md @@ -91,6 +91,24 @@ console gets embedded in the binary. > Prefer `just build all`, which does both for you. The same applies when > you rebuild to deploy an upgrade — re-run with `--features console`. +### Linking a prebuilt DuckDB library + +Default builds include DuckDB and its JSON support. To avoid compiling the +bundled C++ engine on a constrained build host, supply a prebuilt library matching +the DuckDB version required by the locked `libduckdb-sys` crate, and disable the +`bundled-duckdb` default feature: + +```bash +# Run in server/ after building console/dist/. +CARGO_BUILD_JOBS=1 DUCKDB_LIB_DIR=/path/to/matching-duckdb \ + cargo build --locked -p heron --no-default-features --features console +LD_LIBRARY_PATH=/path/to/matching-duckdb ./target/debug/heron --config config.toml +``` + +This produces a dynamically linked binary: keep the matching library available +at runtime. Default standalone backend/API tests continue to use bundled DuckDB; +workspace builds may also opt out with `--workspace --no-default-features`. + ### eBPF on-host TLS capture (experimental, Linux) The [eBPF source](configure.md#ebpf--on-host-tls-capture-linux-experimental) diff --git a/scripts/lint/validated-types.txt b/scripts/lint/validated-types.txt index 2bccebf0..e0dccfd1 100644 --- a/scripts/lint/validated-types.txt +++ b/scripts/lint/validated-types.txt @@ -19,6 +19,8 @@ # every reported caller by migrating to the validator. # `TimeRange` validation lives in to_time_range() at server/h-api/src/params.rs. +# Backend summary regression fixtures use explicit synthetic microsecond ranges; +# the API-only converter is outside the storage crate's dependency boundary. # All API route handlers must funnel through it; tests, in-crate integration # suites, and internal benchmarking tools may construct directly. -TimeRange : server/h-api/src/params.rs server/h-storage/src/query.rs server/**/tests/**.rs server/**/query_tests.rs server/**/concurrent_tests.rs server/**/keepalive_pipeline.rs server/**/keepalive_estimator_integration.rs server/**/duckdb_routes.rs server/**/pipeline_e2e.rs server/**/pcap_extract_route.rs server/h-storage-clickhouse/src/it.rs server/h-storage-aglake/src/it.rs server/app/heron/src/bin/storage_bench.rs +TimeRange : server/h-api/src/params.rs server/h-storage/src/query.rs server/**/tests/**.rs server/**/query_tests.rs server/**/concurrent_tests.rs server/**/keepalive_pipeline.rs server/**/keepalive_estimator_integration.rs server/**/duckdb_routes.rs server/**/pipeline_e2e.rs server/**/pcap_extract_route.rs server/h-storage-clickhouse/src/it.rs server/h-storage-clickhouse/src/summary_tests.rs server/h-storage-aglake/src/it.rs server/h-storage-duckdb/src/journal_read_tests.rs server/app/heron/src/bin/storage_bench.rs diff --git a/server/Cargo.lock b/server/Cargo.lock index 46ec6db2..041d800d 100644 --- a/server/Cargo.lock +++ b/server/Cargo.lock @@ -1582,7 +1582,10 @@ dependencies = [ "h-protocol", "h-storage", "h-turn", + "libc", + "serde", "serde_json", + "sha2", "tempfile", "tokio", "tracing", diff --git a/server/Cargo.toml b/server/Cargo.toml index 51dca4fd..9a2b8756 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -79,7 +79,7 @@ h-export = { path = "h-export" } h-turn = { path = "h-turn" } h-metrics = { path = "h-metrics" } h-storage = { path = "h-storage" } -h-storage-duckdb = { path = "h-storage-duckdb" } +h-storage-duckdb = { path = "h-storage-duckdb", default-features = false } h-storage-clickhouse = { path = "h-storage-clickhouse" } h-storage-aglake = { path = "h-storage-aglake" } h-pcap-extract = { path = "h-pcap-extract" } @@ -91,7 +91,7 @@ mime_guess = "2" # bugs behind the prod outage — #22591 (ARTOperator::Delete on nested leaf), # #22094 (RemoveFromIndexes / "remove all rows merging checkpoint deltas"), # #22503 (BlockAllocator invalid memory access → the SIGSEGV). Cargo.lock pins it. -duckdb = { version = "1", features = ["bundled", "json"] } +duckdb = { version = "1" } # ClickHouse backend client — HTTP interface, serde RowBinary, async/Tokio. # lz4 is the crate's default compression; kept explicit for clarity. clickhouse = { version = "0.15", features = ["lz4"] } @@ -103,4 +103,4 @@ clickhouse = { version = "0.15", features = ["lz4"] } reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "http2", "gzip"] } chrono = "0.4" tdigest = "0.2" -h-api = { path = "h-api" } +h-api = { path = "h-api", default-features = false } diff --git a/server/app/heron/Cargo.toml b/server/app/heron/Cargo.toml index d29e11fe..3c4e95fa 100644 --- a/server/app/heron/Cargo.toml +++ b/server/app/heron/Cargo.toml @@ -35,6 +35,9 @@ rust-embed = { workspace = true, optional = true } mime_guess = { workspace = true, optional = true } [features] +default = ["bundled-duckdb"] +# Disable default features and set DUCKDB_LIB_DIR to use a matching system library. +bundled-duckdb = ["h-storage-duckdb/bundled-duckdb", "h-api/bundled-duckdb"] console = ["dep:rust-embed", "dep:mime_guess"] # Forwards to h-capture's `ebpf` feature so a release binary can be built with # on-host SSL-uprobe capture: `cargo build --bin heron --features "console ebpf"`. diff --git a/server/app/heron/src/lib.rs b/server/app/heron/src/lib.rs index b894894a..905a2372 100644 --- a/server/app/heron/src/lib.rs +++ b/server/app/heron/src/lib.rs @@ -23,7 +23,14 @@ use h_storage_duckdb::DuckDbBackend; /// crate. pub fn create_backend(config: &StorageConfig) -> Result> { match config.backend.as_str() { - "duckdb" => Ok(Arc::new(DuckDbBackend::open(&config.duckdb.path)?)), + "duckdb" => { + if config.duckdb.journal && config.retention.enabled { + return Err(AppError::Config( + "DuckDB journal mode requires storage.retention.enabled=false; manage the database and its journal directory together".into(), + )); + } + Ok(Arc::new(DuckDbBackend::open_configured(&config.duckdb)?)) + } "clickhouse" => Ok(Arc::new(ClickHouseBackend::new(&config.clickhouse)?)), // Only the current spelling needs an arm: `AppConfig::load` normalizes // the pre-0.3 `"sglake"` before anything reaches here. A config built @@ -49,6 +56,22 @@ mod tests { assert!(create_backend(&config).is_ok()); } + #[test] + fn journal_rejects_automatic_row_retention() { + let mut config = StorageConfig::default(); + config.duckdb.journal = true; + assert!(matches!(create_backend(&config), Err(AppError::Config(_)))); + } + + #[test] + fn journal_requires_an_on_disk_database() { + let mut config = StorageConfig::default(); + config.duckdb.path = ":memory:".into(); + config.duckdb.journal = true; + config.retention.enabled = false; + assert!(matches!(create_backend(&config), Err(AppError::Config(_)))); + } + #[test] fn test_create_backend_unknown() { let mut config = StorageConfig::default(); diff --git a/server/app/heron/src/main.rs b/server/app/heron/src/main.rs index 0621cd3b..5b85427a 100644 --- a/server/app/heron/src/main.rs +++ b/server/app/heron/src/main.rs @@ -9,10 +9,6 @@ use tracing::level_filters::LevelFilter; use tracing_subscriber::fmt::time::UtcTime; use tracing_subscriber::FmtSubscriber; -use heron::create_backend; -use heron::Pipeline; -use tokio::task::JoinSet; -use tokio_util::sync::CancellationToken; use h_common::config::{ config_search_paths, discover_config_path, AppConfig, CaptureSourceConfig, PipelineDef, }; @@ -20,11 +16,15 @@ use h_common::internal_metrics::{ AggregateHistory, HistoryRecorder, Metric, MetricsReporter, MetricsSystem, }; use h_llm::agent_classifier::ClassifierConfig; +use heron::create_backend; +use heron::Pipeline; +use tokio::task::JoinSet; +use tokio_util::sync::CancellationToken; mod cmd; const CAPTURE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3); -const PIPELINE_DRAIN_TIMEOUT: Duration = Duration::from_secs(5); +const PIPELINE_DRAIN_TIMEOUT: Duration = Duration::from_secs(60); const API_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3); const RETENTION_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(3); @@ -196,6 +196,28 @@ async fn join_capture_tasks(capture_tasks: &mut JoinSet<()>) { while capture_tasks.join_next().await.is_some() {} } +fn supervisor_drained( + result: Result, tokio::task::JoinError>, + cancel: &CancellationToken, +) -> bool { + match result { + Ok(Some((label, err))) => { + tracing::error!("pipeline stage '{label}' exited abnormally: {err}"); + cancel.cancel(); + false + } + Ok(None) => { + tracing::info!("all pipeline stages exited cleanly"); + true + } + Err(e) => { + tracing::error!("supervisor join error: {e}"); + cancel.cancel(); + false + } + } +} + #[tokio::main] async fn main() { let cli = Cli::parse(); @@ -307,16 +329,15 @@ async fn run_pipeline(cli: Cli) { config.pipelines.clone() }; - let pcap_extract_roots: std::sync::Arc> = - std::sync::Arc::new( - effective_pipelines - .iter() - .map(|def| h_pcap_extract::PipelineRoot { - name: def.name.clone(), - dump_dir: std::path::PathBuf::from(&def.pcap_dump.dir), - }) - .collect(), - ); + let pcap_extract_roots: std::sync::Arc> = std::sync::Arc::new( + effective_pipelines + .iter() + .map(|def| h_pcap_extract::PipelineRoot { + name: def.name.clone(), + dump_dir: std::path::PathBuf::from(&def.pcap_dump.dir), + }) + .collect(), + ); // Validate no duplicate source_ids across all pipeline sources. { @@ -764,14 +785,12 @@ async fn run_pipeline(cli: Cli) { // Drop our clone — spawned tasks hold theirs. } - // Wait for: ctrl-c, all capture sources finishing, or any pipeline - // stage task panicking. Only the signal arm cancels eagerly — the - // other two arms let the pipeline drain naturally (`Pipeline::supervise` - // returns when every stage's upstream sender drops) and fall through - // to the post-drain park below, so the API/console stays available - // for inspection. `--exit-after-drain` short-circuits the park. + // Wait for ctrl-c, capture EOF, or supervisor completion. A signal or + // supervisor failure cancels capture immediately. Clean EOF still + // drains naturally and keeps the API available for inspection unless + // --exit-after-drain is set. let mut supervisor = tokio::spawn(Pipeline::supervise(stage_handles)); - let mut supervisor_done = false; + let mut supervisor_result = None; tokio::select! { sig = wait_shutdown_signal() => { tracing::info!("received {sig}, stopping..."); @@ -783,14 +802,7 @@ async fn run_pipeline(cli: Cli) { tracing::info!("all capture sources finished"); } res = &mut supervisor => { - supervisor_done = true; - match res { - Ok(Some((label, err))) => tracing::error!( - "pipeline stage '{label}' exited abnormally: {err}" - ), - Ok(None) => tracing::info!("all pipeline stages exited cleanly"), - Err(e) => tracing::error!("supervisor join error: {e}"), - } + supervisor_result = Some(supervisor_drained(res, &cancel)); } } @@ -817,32 +829,23 @@ async fn run_pipeline(cli: Cli) { "capture source(s) did not stop in time; forcing shutdown" ); capture_tasks.abort_all(); + cancel.cancel(); force_exit = true; } tracing::info!("waiting for pipeline (incl. storage sink) to drain..."); - let pipeline_drained = if supervisor_done { - tracing::info!("pipeline already drained during shutdown"); - true + let pipeline_drained = if let Some(result) = supervisor_result { + tracing::info!("pipeline already completed during shutdown"); + result } else { match tokio::time::timeout(PIPELINE_DRAIN_TIMEOUT, &mut supervisor).await { - Ok(Ok(Some((label, err)))) => { - tracing::error!("pipeline stage '{label}' exited abnormally: {err}"); - true - } - Ok(Ok(None)) => { - tracing::info!("all pipeline stages drained cleanly"); - true - } - Ok(Err(e)) => { - tracing::error!("supervisor join error: {e}"); - true - } + Ok(result) => supervisor_drained(result, &cancel), Err(_) => { tracing::error!( timeout_secs = PIPELINE_DRAIN_TIMEOUT.as_secs(), "pipeline drain timed out; forcing shutdown" ); + cancel.cancel(); force_exit = true; false } @@ -850,6 +853,8 @@ async fn run_pipeline(cli: Cli) { }; if pipeline_drained { tracing::info!("pipeline drained"); + } else { + force_exit = true; } // Stop reporters now that drain is done — their final tick captures @@ -876,7 +881,7 @@ async fn run_pipeline(cli: Cli) { // post-drain inspection — unless the user opted into batch mode with // `--exit-after-drain`, or a real signal already fired `cancel` (in // which case the API is already on its way down). - if !cancel.is_cancelled() { + if pipeline_drained && !force_exit && !cancel.is_cancelled() { drained.store(true, Ordering::Release); if cli.run.exit_after_drain { tracing::info!("pipeline drained; --exit-after-drain set, exiting"); @@ -893,7 +898,7 @@ async fn run_pipeline(cli: Cli) { } if force_exit { - tracing::error!("graceful shutdown stalled; exiting forcefully"); + tracing::error!("pipeline failed or shutdown stalled; exiting unsuccessfully"); std::process::exit(1); } } else { @@ -1017,6 +1022,63 @@ mod tests { use std::time::Duration; use tokio::task::JoinHandle; + fn test_stage() -> heron::StageTask { + heron::StageTask { + stage: "synthetic_stage", + shard: None, + pipeline: None, + shutdown: None, + } + } + + #[tokio::test] + async fn panicked_pipeline_stage_is_not_drained() { + let stage = tokio::spawn(async { panic!("synthetic stage failure") }); + let supervisor = tokio::spawn(Pipeline::supervise(vec![(test_stage(), stage)])); + let result = supervisor.await; + assert!(matches!(&result, Ok(Some((_, error))) if error.is_panic())); + let cancel = CancellationToken::new(); + assert!( + !supervisor_drained(result, &cancel), + "a panicked pipeline stage must not report a successful drain" + ); + assert!( + cancel.is_cancelled(), + "stage failure must cancel capture immediately" + ); + } + + #[tokio::test] + async fn panicked_supervisor_is_not_drained() { + let supervisor = tokio::spawn(async { + panic!("synthetic supervisor failure"); + #[allow(unreachable_code)] + None::<(heron::StageTask, tokio::task::JoinError)> + }); + let result = supervisor.await; + assert!(matches!(&result, Err(error) if error.is_panic())); + let cancel = CancellationToken::new(); + assert!( + !supervisor_drained(result, &cancel), + "a panicked supervisor must not report a successful drain" + ); + assert!( + cancel.is_cancelled(), + "supervisor failure must cancel capture immediately" + ); + } + + #[tokio::test] + async fn clean_pipeline_supervisor_is_drained() { + let stage = tokio::spawn(async {}); + let supervisor = tokio::spawn(Pipeline::supervise(vec![(test_stage(), stage)])); + let result = supervisor.await; + assert!(matches!(&result, Ok(None))); + let cancel = CancellationToken::new(); + assert!(supervisor_drained(result, &cancel)); + assert!(!cancel.is_cancelled()); + } + /// Simulates the shutdown coordinator's drain path when the supervisor /// JoinHandle has already completed in the select! block. Verifies that /// the `supervisor_done` flag prevents double-polling. diff --git a/server/app/heron/src/pipeline.rs b/server/app/heron/src/pipeline.rs index 102660aa..2f7b0f0c 100644 --- a/server/app/heron/src/pipeline.rs +++ b/server/app/heron/src/pipeline.rs @@ -43,6 +43,7 @@ use std::sync::Arc; use tokio::sync::mpsc::{self, WeakSender}; use tokio::task::{JoinHandle, JoinSet}; +use tokio_util::sync::CancellationToken; use h_capture::{RawPacket, RoutingSender}; use h_common::config::{CaptureSourceConfig, PipelineDef}; @@ -71,6 +72,9 @@ pub struct StageTask { pub stage: &'static str, pub shard: Option, pub pipeline: Option, + /// Housekeeping stop signal. Finite stages use `None`; housekeeping is + /// stopped only after every finite stage, including storage, has joined. + pub shutdown: Option, } impl fmt::Display for StageTask { @@ -283,6 +287,7 @@ impl Pipeline { stage: "dispatcher", shard: if dispatcher_count > 1 { Some(i) } else { None }, pipeline: Some(name.clone()), + shutdown: None, }, handle, )); @@ -300,6 +305,7 @@ impl Pipeline { stage: "protocol", shard: Some(j), pipeline: Some(name.clone()), + shutdown: None, }, h, )); @@ -323,6 +329,7 @@ impl Pipeline { stage: "joiner", shard: Some(j), pipeline: Some(name.clone()), + shutdown: None, }, h, )); @@ -350,6 +357,7 @@ impl Pipeline { stage: "llm", shard: Some(j), pipeline: Some(name.clone()), + shutdown: None, }, h, )); @@ -373,6 +381,7 @@ impl Pipeline { stage: "turn", shard: Some(j), pipeline: Some(name.clone()), + shutdown: None, }, h, )); @@ -394,6 +403,7 @@ impl Pipeline { stage: "metrics", shard: Some(j), pipeline: Some(name.clone()), + shutdown: None, }, h, )); @@ -523,22 +533,25 @@ impl Pipeline { stage: "storage_sink", shard: None, pipeline: None, + shutdown: None, }, sink_handle, )); - // Pair-detection sweeper — scans recently-finalized turns for - // llmproxy duplicates (real haproxy hops + multi-interface - // double-capture) and folds them by writing pair annotations - // back to `agent_turns.metadata`. Runs forever, owns its own - // Arc. - let pair_sweeper_handle = - h_storage::spawn_pair_sweeper(h_storage::PairSweeperConfig::default(), storage); + // Pair-detection sweeper — folds duplicate turns. The supervisor + // requests a final sweep only after the storage sink has drained. + let pair_sweeper_shutdown = CancellationToken::new(); + let pair_sweeper_handle = h_storage::spawn_pair_sweeper_with_shutdown( + h_storage::PairSweeperConfig::default(), + storage, + pair_sweeper_shutdown.clone(), + ); stage_handles.push(( StageTask { stage: "pair_sweeper", shard: None, pipeline: None, + shutdown: Some(pair_sweeper_shutdown), }, pair_sweeper_handle, )); @@ -561,21 +574,59 @@ impl Pipeline { handles: Vec<(StageTask, JoinHandle<()>)>, ) -> Option<(StageTask, tokio::task::JoinError)> { let mut set: JoinSet<(StageTask, Result<(), tokio::task::JoinError>)> = JoinSet::new(); - for (label, h) in handles { - set.spawn(async move { - let res = h.await; - (label, res) - }); + // Housekeeping has no EOF. Explicit stop signals keep its lifecycle + // independent of display labels and let in-flight work finish. + let mut finite = handles + .iter() + .filter(|(label, _)| label.shutdown.is_none()) + .count(); + let shutdowns: Vec<_> = handles + .iter() + .filter_map(|(label, _)| label.shutdown.clone()) + .collect(); + let mut aborts = Vec::with_capacity(handles.len()); + for (label, handle) in handles { + aborts.push(handle.abort_handle()); + let handle = tokio_util::task::AbortOnDropHandle::new(handle); + set.spawn(async move { (label, handle.await) }); + } + let mut failure = None; + while finite > 0 { + let Some(joined) = set.join_next().await else { + break; + }; + let (label, result) = joined.expect("supervise wrapper task joined cleanly"); + if let Err(error) = result { + failure = Some((label, error)); + break; + } + if label.shutdown.is_none() { + finite -= 1; + } + } + if failure.is_some() { + for handle in &aborts { + handle.abort(); + } + } else { + // All finite stages have actually joined, including the sink's + // final flush. Housekeeping can now see every persisted turn. + for shutdown in shutdowns { + shutdown.cancel(); + } } while let Some(joined) = set.join_next().await { - // The outer join never panics (its body just awaits another - // handle); unwrap is safe. - let (label, res) = joined.expect("supervise wrapper task joined cleanly"); - if let Err(e) = res { - return Some((label, e)); + let (label, result) = joined.expect("supervise wrapper task joined cleanly"); + if let Err(error) = result { + if failure.is_none() { + failure = Some((label, error)); + for handle in &aborts { + handle.abort(); + } + } } } - None + failure } } @@ -592,3 +643,198 @@ fn make_shard_channels( } (txs, rxs) } + +#[cfg(test)] +mod drain_tests { + use super::*; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::time::Duration; + use tokio::sync::Notify; + use tokio_util::task::AbortOnDropHandle; + + #[tokio::test] + async fn supervisor_does_not_abort_housekeeping_between_member_writes() { + let members_written = Arc::new(AtomicUsize::new(0)); + let first_written = Arc::new(Notify::new()); + let release_second = Arc::new(Notify::new()); + let shutdown = CancellationToken::new(); + let sweeper = tokio::spawn({ + let members_written = members_written.clone(); + let first_written = first_written.clone(); + let release_second = release_second.clone(); + let shutdown = shutdown.clone(); + async move { + members_written.store(1, Ordering::SeqCst); + first_written.notify_one(); + release_second.notified().await; + members_written.store(2, Ordering::SeqCst); + shutdown.cancelled().await; + } + }); + first_written.notified().await; + let finite = tokio::spawn(async {}); + let mut supervised = AbortOnDropHandle::new(tokio::spawn(Pipeline::supervise(vec![ + ( + StageTask { + stage: "storage_sink", + shard: None, + pipeline: None, + shutdown: None, + }, + finite, + ), + ( + StageTask { + stage: "maintenance", + shard: None, + pipeline: None, + shutdown: Some(shutdown), + }, + sweeper, + ), + ]))); + + assert!( + tokio::time::timeout(Duration::from_millis(30), &mut supervised) + .await + .is_err(), + "finite EOF must wait for the in-flight housekeeping batch" + ); + release_second.notify_one(); + assert!(tokio::time::timeout(Duration::from_secs(1), supervised) + .await + .expect("housekeeping must drain") + .unwrap() + .is_none()); + assert_eq!( + members_written.load(Ordering::SeqCst), + 2, + "shutdown must preserve both members of the pair" + ); + } + + #[tokio::test] + async fn supervisor_joins_storage_before_waiting_for_final_housekeeping() { + let storage_release = Arc::new(Notify::new()); + let storage_drained = Arc::new(AtomicBool::new(false)); + let final_release = Arc::new(Notify::new()); + let final_completed = Arc::new(AtomicBool::new(false)); + let shutdown = CancellationToken::new(); + let storage = tokio::spawn({ + let storage_release = storage_release.clone(); + let storage_drained = storage_drained.clone(); + async move { + storage_release.notified().await; + storage_drained.store(true, Ordering::SeqCst); + } + }); + let sweeper = tokio::spawn({ + let final_release = final_release.clone(); + let final_completed = final_completed.clone(); + let storage_drained = storage_drained.clone(); + let shutdown = shutdown.clone(); + async move { + shutdown.cancelled().await; + assert!( + storage_drained.load(Ordering::SeqCst), + "housekeeping stop must follow storage join" + ); + final_release.notified().await; + final_completed.store(true, Ordering::SeqCst); + } + }); + let mut supervised = AbortOnDropHandle::new(tokio::spawn(Pipeline::supervise(vec![ + ( + StageTask { + stage: "llm", + shard: None, + pipeline: None, + shutdown: None, + }, + tokio::spawn(async {}), + ), + ( + StageTask { + stage: "storage_sink", + shard: None, + pipeline: None, + shutdown: None, + }, + storage, + ), + ( + StageTask { + stage: "pair_sweeper", + shard: None, + pipeline: None, + shutdown: Some(shutdown.clone()), + }, + sweeper, + ), + ]))); + + assert!( + tokio::time::timeout(Duration::from_millis(30), &mut supervised) + .await + .is_err(), + "upstream EOF must not bypass the storage sink join" + ); + assert!(!storage_drained.load(Ordering::SeqCst)); + assert!(!shutdown.is_cancelled(), "stop must wait for storage join"); + storage_release.notify_one(); + assert!( + tokio::time::timeout(Duration::from_millis(30), &mut supervised) + .await + .is_err(), + "storage EOF must still wait for final housekeeping" + ); + assert!(storage_drained.load(Ordering::SeqCst)); + final_release.notify_one(); + assert!(tokio::time::timeout(Duration::from_secs(1), supervised) + .await + .expect("final housekeeping must finish") + .unwrap() + .is_none()); + assert!(final_completed.load(Ordering::SeqCst)); + } + + #[tokio::test] + async fn supervisor_reports_final_housekeeping_failure() { + let shutdown = CancellationToken::new(); + let sweeper = tokio::spawn({ + let shutdown = shutdown.clone(); + async move { + shutdown.cancelled().await; + panic!("final maintenance failed"); + } + }); + let result = tokio::time::timeout( + Duration::from_secs(1), + Pipeline::supervise(vec![ + ( + StageTask { + stage: "storage_sink", + shard: None, + pipeline: None, + shutdown: None, + }, + tokio::spawn(async {}), + ), + ( + StageTask { + stage: "maintenance", + shard: None, + pipeline: None, + shutdown: Some(shutdown), + }, + sweeper, + ), + ]), + ) + .await + .expect("failed housekeeping must terminate supervision"); + let (label, error) = result.expect("final maintenance failure must be returned"); + assert_eq!(label.stage, "maintenance"); + assert!(error.is_panic()); + } +} diff --git a/server/app/heron/tests/pipeline_e2e.rs b/server/app/heron/tests/pipeline_e2e.rs index 6860ec12..9ae1eaa7 100644 --- a/server/app/heron/tests/pipeline_e2e.rs +++ b/server/app/heron/tests/pipeline_e2e.rs @@ -16,8 +16,6 @@ use duckdb::Connection; use tempfile::TempDir; use tokio_util::sync::CancellationToken; -use heron::create_backend; -use heron::Pipeline; use h_capture::{CaptureSource, PcapFileSource}; use h_common::config::{ CaptureSourceConfig, DuckDbConfig, PipelineDef, RetentionConfig, StorageConfig, @@ -25,6 +23,8 @@ use h_common::config::{ }; use h_common::internal_metrics::{Metric, MetricsSystem}; use h_llm::wire_apis as wa; +use heron::create_backend; +use heron::Pipeline; fn fixture(name: &str) -> Option { // Corpus first (the committed, git-LFS fixtures CI pulls), then the legacy @@ -54,6 +54,7 @@ fn build_storage_config(db_path: &str) -> StorageConfig { backend: "duckdb".into(), duckdb: DuckDbConfig { path: db_path.into(), + ..Default::default() }, sink: StorageSinkConfig::default(), retention: RetentionConfig::default(), @@ -406,7 +407,9 @@ async fn two_pcaps_isolated_but_metrics_merged() { "expected 2 distinct source_ids in llm_metrics, got {source_ids:?}" ); assert!( - source_ids.iter().any(|s| s == "claude-cli-anthropic-stream"), + source_ids + .iter() + .any(|s| s == "claude-cli-anthropic-stream"), "expected 'claude-cli-anthropic-stream' source_id, got {source_ids:?}" ); assert!( @@ -445,7 +448,10 @@ async fn all_corpus_fixtures_reach_storage() { let metrics = count(&conn, "llm_metrics"); eprintln!("all-corpus rows: calls={calls} turns={turns} metrics={metrics}"); - assert!(calls >= fixtures.len() as i64, "expected >=1 span per fixture, got {calls}"); + assert!( + calls >= fixtures.len() as i64, + "expected >=1 span per fixture, got {calls}" + ); assert!(turns >= 1, "expected >=1 trace, got {turns}"); // Every fixture is a distinct source_id, and each must land in llm_metrics diff --git a/server/config/default.toml b/server/config/default.toml index 93fbbcac..ba9e2a50 100644 --- a/server/config/default.toml +++ b/server/config/default.toml @@ -117,6 +117,15 @@ backend = "duckdb" [storage.duckdb] path = "data/heron.duckdb" +# Optional positive limits; omitted values preserve DuckDB defaults. +# threads = 1 +# memory_limit_mb = 768 +# read_pool_size = 1 +# Optional allocator housekeeping; omitted preserves DuckDB's default. +# allocator_background_threads = true +# Optional append-only payload/record journal with asynchronous metadata indexing. +# Requires an on-disk path and storage.retention.enabled=false; defaults to false. +# journal = false # ClickHouse backend (used only when backend = "clickhouse"). Talks to the # server over its HTTP interface (default port 8123). The target database is diff --git a/server/h-api/Cargo.toml b/server/h-api/Cargo.toml index d5945b26..3ecfa2b9 100644 --- a/server/h-api/Cargo.toml +++ b/server/h-api/Cargo.toml @@ -20,6 +20,12 @@ tracing.workspace = true tower-http.workspace = true chrono = { workspace = true } +[features] +# Keep standalone API tests self-contained; workspace --no-default-features +# can use a matching system DuckDB library instead. +default = ["bundled-duckdb"] +bundled-duckdb = ["h-storage-duckdb/bundled-duckdb"] + [dev-dependencies] tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" diff --git a/server/h-capture/src/pcap_live.rs b/server/h-capture/src/pcap_live.rs index b14b119e..def091d4 100644 --- a/server/h-capture/src/pcap_live.rs +++ b/server/h-capture/src/pcap_live.rs @@ -123,19 +123,15 @@ impl CaptureSource for PcapLiveSource { crate::CaptureError::Other(format!("interface '{}' not found", interface)) })?; - // 16 MiB AF_PACKET ring. The libpcap default (~2 MiB) is too - // small to absorb bursts of GRO-coalesced super-segments - // (10–60 KB each) that Linux generates on `-i any` for TCP flows - // carrying large LLM prompts/SSE bodies. Side-effect of an - // undersized ring is silent loss that does NOT show up in - // `pcap_stats().dropped` under TPACKET_V3 + immediate_mode, - // because dropped packets never reach the per-socket ring. - // 16 MiB matches what `tcpdump -B 16384` users typically pick - // for chatty TLS / SSE workloads. + // Reserve a bounded burst buffer per live source. Large loopback/GRO + // packets can fill a small ring while the capture thread is briefly + // descheduled or waiting on its downstream queue. This adds buffering + // headroom; sustained overload can still cause kernel packet drops. + const CAPTURE_BUFFER_BYTES: i32 = 64 * 1024 * 1024; let mut cap = Capture::from_device(device)? .immediate_mode(true) .snaplen(snaplen as i32) - .buffer_size(16 * 1024 * 1024) + .buffer_size(CAPTURE_BUFFER_BYTES) .timeout(500) // 500ms read timeout for shutdown responsiveness .open()?; @@ -152,10 +148,11 @@ impl CaptureSource for PcapLiveSource { let link_type = cap.get_datalink().0 as u32; tracing::info!( - "pcap-live: capturing on {} (link_type={}, snaplen={})", + "pcap-live: capturing on {} (link_type={}, snaplen={}, requested_buffer_bytes={})", interface, link_type, snaplen, + CAPTURE_BUFFER_BYTES, ); let mut count: u64 = 0; diff --git a/server/h-common/src/config.rs b/server/h-common/src/config.rs index 25cf75e8..1677625f 100644 --- a/server/h-common/src/config.rs +++ b/server/h-common/src/config.rs @@ -741,12 +741,34 @@ pub const LEGACY_AGLAKE_BACKEND: &str = "sglake"; pub struct DuckDbConfig { #[serde(default = "default_duckdb_path")] pub path: String, + /// DuckDB worker threads. None preserves DuckDB's automatic sizing. + #[serde(default)] + pub threads: Option, + /// Memory budget for the shared database instance, in decimal MB. + #[serde(default)] + pub memory_limit_mb: Option, + /// Number of pooled query connections (writers share the same instance). + #[serde(default)] + pub read_pool_size: Option, + /// Let DuckDB's allocator purge unused pages in the background, where supported. + /// None preserves DuckDB's default allocator policy. + #[serde(default)] + pub allocator_background_threads: Option, + /// Persist records to a local segmented journal before asynchronous indexing. + /// Requires an on-disk database and explicit journal-directory lifecycle management. + #[serde(default)] + pub journal: bool, } impl Default for DuckDbConfig { fn default() -> Self { Self { path: default_duckdb_path(), + threads: None, + memory_limit_mb: None, + read_pool_size: None, + allocator_background_threads: None, + journal: false, } } } @@ -3455,3 +3477,27 @@ mod phase2_tests { ); } } + +#[cfg(test)] +mod resource_config_tests { + use super::*; + #[test] + fn duckdb_resource_limits_survive_config_loading() { + let cfg = AppConfig::from_toml( + r#"[storage.duckdb] +path = ":memory:" +threads = 1 +memory_limit_mb = 256 +read_pool_size = 1 +allocator_background_threads = true +journal = true +"#, + ); + let json = serde_json::to_value(cfg.storage.duckdb).unwrap(); + assert_eq!(json["threads"], 1); + assert_eq!(json["memory_limit_mb"], 256); + assert_eq!(json["read_pool_size"], 1); + assert_eq!(json["allocator_background_threads"], true); + assert_eq!(json["journal"], true); + } +} diff --git a/server/h-llm/src/agents/codex_cli.rs b/server/h-llm/src/agents/codex_cli.rs index a5f7bcca..6735a76a 100644 --- a/server/h-llm/src/agents/codex_cli.rs +++ b/server/h-llm/src/agents/codex_cli.rs @@ -520,7 +520,7 @@ mod tests { fn is_turn_terminal_delegates_to_wire_api_helper() { // Behavioral coverage lives in wire_apis::openai::responses::terminal_helper_tests. // This test only confirms the profile actually delegates to that helper. - let body = r#"{"output":[{"type":"message","role":"assistant","content":[]}]}"#; + let body = r#"{"status":"completed","output":[{"type":"message","role":"assistant","content":[]}]}"#; let mut c = call_with(wa::OPENAI_RESPONSES, vec![], None); c.set_response_body(body); let wa_reg = crate::wire_apis::build_default_wire_api_registry(); diff --git a/server/h-llm/src/agents/generic.rs b/server/h-llm/src/agents/generic.rs index ab23395d..152b860c 100644 --- a/server/h-llm/src/agents/generic.rs +++ b/server/h-llm/src/agents/generic.rs @@ -1200,7 +1200,7 @@ mod tests { #[test] fn is_turn_terminal_delegates_to_helper() { - let r = r#"{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; + let r = r#"{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; let mut c = resp(None, Some(r)); let wires = crate::wire_apis::build_default_wire_api_registry(); assert!(GenericProfile.is_turn_terminal(&c.ctx(), &wires)); diff --git a/server/h-llm/src/agents/hermes.rs b/server/h-llm/src/agents/hermes.rs index 56f19a86..9b2f3fd8 100644 --- a/server/h-llm/src/agents/hermes.rs +++ b/server/h-llm/src/agents/hermes.rs @@ -489,7 +489,7 @@ mod tests { #[test] fn is_turn_terminal_openai_responses_uses_body_only_check() { let wires = crate::wire_apis::build_default_wire_api_registry(); - let resp_terminal = r#"{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; + let resp_terminal = r#"{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; let mut c = call(wa::OPENAI_RESPONSES, None, Some(resp_terminal)); assert!(HermesProfile.is_turn_terminal(&c.ctx(), &wires)); c.set_response_body( diff --git a/server/h-llm/src/agents/openclaw.rs b/server/h-llm/src/agents/openclaw.rs index 61a5aa85..5860c93a 100644 --- a/server/h-llm/src/agents/openclaw.rs +++ b/server/h-llm/src/agents/openclaw.rs @@ -764,7 +764,7 @@ mod tests { // openclaw inspects the response body — `message`-only output is // terminal, presence of any `*_call` is not. let wires = crate::wire_apis::build_default_wire_api_registry(); - let resp_terminal = r#"{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; + let resp_terminal = r#"{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]}"#; let mut c = call(wa::OPENAI_RESPONSES, None, Some(resp_terminal)); assert!(OpenClawProfile.is_turn_terminal(&c.ctx(), &wires)); c.set_response_body( diff --git a/server/h-llm/src/wire_apis/openai/chat.rs b/server/h-llm/src/wire_apis/openai/chat.rs index 4e4122d1..8d7aacd2 100644 --- a/server/h-llm/src/wire_apis/openai/chat.rs +++ b/server/h-llm/src/wire_apis/openai/chat.rs @@ -172,8 +172,9 @@ fn extract_response(resp: &HttpResponseData, resp_body: &ParsedJson) -> Response /// Walk Chat Completions SSE chunks in a single pass, accumulating both the /// numerical fields and the deltas needed to reconstruct a non-streaming -/// `choices[0].message` response. Events with a non-empty `event_type` are -/// Responses events and are silently skipped. +/// `choices[0].message` response. Generic SSE messages may carry Chat chunks +/// or errors; specific Responses event names are silently skipped. +/// Errors are retained alongside any received deltas without inventing finish. /// /// Returns the `ResponseInfo` plus a body-bound `ParsedJson` cache built /// from the same synthetic `Value`. The string form is serialized once @@ -201,44 +202,75 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { let mut total_tokens: Option = None; let mut cache_read_input_tokens: Option = None; let mut saw_chunk = false; + let mut stream_error: Option = None; for event in events { - if !event.event_type.is_empty() { - continue; // Responses event, not ours + if !matches!(event.event_type.as_str(), "" | "message" | "error") { + continue; // Specific events from another wire API are not ours. } let data: Value = match serde_json::from_str::(&event.data) { Ok(v) if v.is_object() => v, _ => continue, // [DONE] sentinel or malformed }; - saw_chunk = true; + if event.event_type != "error" + && data + .get("type") + .and_then(Value::as_str) + .is_some_and(|kind| kind.starts_with("response.")) + { + continue; + } + let is_error = event.event_type == "error" + || data.get("type").and_then(Value::as_str) == Some("error"); + if let Some(error) = data.get("error").filter(|error| !error.is_null()) { + // Keep the actual error directly accessible as body.error. + stream_error = Some(error.clone()); + } else if is_error { + stream_error = Some(data.clone()); + } + if is_error { + continue; + } if response_id.is_none() { if let Some(id) = data.get("id").and_then(|v| v.as_str()) { response_id = Some(id.to_string()); + saw_chunk = true; } } if model.is_none() { if let Some(m) = data.get("model").and_then(|v| v.as_str()) { model = Some(m.to_string()); + saw_chunk = true; } } if let Some(choice) = data.get("choices").and_then(|c| c.get(0)) { if let Some(fr) = choice.get("finish_reason").and_then(|v| v.as_str()) { finish_reason = Some(fr.to_string()); + saw_chunk = true; } if let Some(delta) = choice.get("delta") { + // A role-only initial chunk is real Chat evidence even before + // content arrives; an empty or unknown delta is not. + if delta.get("role").and_then(Value::as_str).is_some() { + saw_chunk = true; + } if let Some(c) = delta.get("content").and_then(|v| v.as_str()) { content.push_str(c); + saw_chunk = true; } if let Some(r) = delta.get("reasoning_content").and_then(|v| v.as_str()) { reasoning_content.push_str(r); + saw_chunk = true; } if let Some(r) = delta.get("reasoning").and_then(|v| v.as_str()) { reasoning.push_str(r); + saw_chunk = true; } if let Some(tcs) = delta.get("tool_calls").and_then(|v| v.as_array()) { for tc in tcs { + saw_chunk = true; let idx = tc.get("index").and_then(|v| v.as_u64()).unwrap_or(0); let entry = tool_calls .entry(idx) @@ -297,11 +329,15 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { .and_then(|v| v.as_u64()) .map(|v| v as u32) }); + saw_chunk |= input_tokens.is_some() + || output_tokens.is_some() + || total_tokens.is_some() + || cache_read_input_tokens.is_some(); } } } - let synthetic = if saw_chunk { + let mut synthetic = if saw_chunk { Some(build_synthetic_body( model.as_deref(), &content, @@ -317,6 +353,9 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { } else { None }; + if let Some(error) = stream_error { + synthetic.get_or_insert_with(|| json!({}))["error"] = error; + } let response_body = synthetic.as_ref().map(Value::to_string); let response_cache = ParsedJson::from_value(synthetic); @@ -703,8 +742,8 @@ pub fn estimate_output_tokens(resp: &Value, est: &dyn TokenEstimator) -> u32 { #[cfg(test)] mod tests { use super::*; - use std::net::IpAddr; use h_protocol::net::FlowKey; + use std::net::IpAddr; fn make_sse(event_type: &str, data: &str) -> SseEventData { let ip: IpAddr = IpAddr::from([127, 0, 0, 1]); @@ -901,6 +940,356 @@ mod tests { assert!(body.get().is_none()); } + #[test] + fn test_extract_sse_typed_error_preserves_full_payload_without_finish() { + let events = [make_sse( + "error", + r#"{"type":"error","code":"server_error","message":"synthetic failure","param":null,"sequence_number":7,"details":{"retryable":true}}"#, + )]; + let (info, body) = extract_sse(&events); + let value = body.get().expect("received error must survive extraction"); + assert_eq!( + value["error"], + json!({ + "type": "error", + "code": "server_error", + "message": "synthetic failure", + "param": null, + "sequence_number": 7, + "details": {"retryable": true} + }) + ); + assert!(value.get("choices").is_none()); + assert!(value.get("status").is_none()); + assert!(info.finish_reason.is_none()); + assert!(info.response_id.is_none()); + assert!(info.model.is_none()); + assert!(info.input_tokens.is_none()); + assert!(info.output_tokens.is_none()); + assert_eq!( + serde_json::from_str::(info.response_body.as_deref().unwrap()).unwrap(), + *value + ); + } + + #[test] + fn test_extract_sse_nested_error_is_directly_accessible_for_generic_events() { + // Wrapping the whole envelope as `error` would hide the actual error + // behind `error.error` and drop the UI's direct code/message lookup. + for event_type in ["", "message", "error"] { + let (info, body) = extract_sse(&[make_sse( + event_type, + r#"{"error":{"type":"server_error","code":"upstream_failed","message":"synthetic failure","param":null,"details":{"received":[1,2],"retryable":false}}}"#, + )]); + let value = body.get().expect("nested error must survive extraction"); + assert_eq!( + value["error"], + json!({ + "type": "server_error", + "code": "upstream_failed", + "message": "synthetic failure", + "param": null, + "details": {"received": [1, 2], "retryable": false} + }), + "event_type={event_type:?}" + ); + assert!(value.get("choices").is_none()); + assert!(value.get("status").is_none()); + assert!(info.finish_reason.is_none()); + assert!(info.response_id.is_none()); + assert!(info.model.is_none()); + assert!(info.response_body.is_some()); + } + } + + #[test] + fn test_extract_sse_flat_error_payload_type_is_used_for_generic_events() { + for event_type in ["", "message"] { + let (info, body) = extract_sse(&[make_sse( + event_type, + r#"{"type":"error","code":"server_error","message":"synthetic failure","sequence_number":9}"#, + )]); + let value = body.get().expect("generic error must survive extraction"); + assert_eq!( + value["error"], + json!({ + "type": "error", + "code": "server_error", + "message": "synthetic failure", + "sequence_number": 9 + }), + "event_type={event_type:?}" + ); + assert!(value.get("choices").is_none()); + assert!(value.get("status").is_none()); + assert!(info.finish_reason.is_none()); + } + } + + #[test] + fn test_extract_sse_generic_message_keeps_chat_deltas_and_metadata() { + let events = [ + make_sse( + "message", + r#"{"id":"chatcmpl-generic","model":"synthetic-model","choices":[{"index":0,"delta":{"role":"assistant","content":"Hello"}}]}"#, + ), + make_sse( + "message", + r#"{"id":"chatcmpl-later","model":"later-model","choices":[{"index":0,"delta":{"content":" world"}}]}"#, + ), + make_sse( + "message", + r#"{"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}"#, + ), + make_sse( + "message", + r#"{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"prompt_tokens_details":{"cached_tokens":3}}}"#, + ), + make_sse("message", "[DONE]"), + ]; + let (info, body) = extract_sse(&events); + let value = body.get().expect("generic message is a valid Chat event"); + assert_eq!(info.response_id.as_deref(), Some("chatcmpl-generic")); + assert_eq!(info.model.as_deref(), Some("synthetic-model")); + assert_eq!(info.finish_reason.as_deref(), Some("stop")); + assert_eq!(info.input_tokens, Some(10)); + assert_eq!(info.output_tokens, Some(5)); + assert_eq!(info.total_tokens, Some(15)); + assert_eq!(info.cache_read_input_tokens, Some(3)); + assert_eq!(value["model"], "synthetic-model"); + assert_eq!(value["choices"][0]["message"]["content"], "Hello world"); + assert_eq!(value["choices"][0]["finish_reason"], "stop"); + assert_eq!(value["usage"]["prompt_tokens"], 10); + assert_eq!(value["usage"]["completion_tokens"], 5); + assert_eq!(value["usage"]["total_tokens"], 15); + assert_eq!(value["usage"]["prompt_tokens_details"]["cached_tokens"], 3); + assert!(value.get("error").is_none()); + } + + // @scenario LLM-STREAM-EVIDENCE-001 unit + #[test] + fn test_extract_sse_error_keeps_partial_text_reasoning_and_tool_calls() { + for error_event_type in ["error", "", "message"] { + let events = [ + make_sse( + "", + r#"{"id":"chatcmpl-partial","model":"synthetic-model","choices":[{"index":0,"delta":{"content":"partial ","reasoning_content":"first ","reasoning":"step ","tool_calls":[{"index":0,"id":"call_partial","function":{"name":"lookup","arguments":"{\"city\":"}}]}}]}"#, + ), + make_sse( + "", + r#"{"choices":[{"index":0,"delta":{"content":"answer","reasoning_content":"thought","reasoning":"one","tool_calls":[{"index":0,"function":{"arguments":"\"synthetic"}},{"index":3,"id":"call_other","function":{"name":"other","arguments":"{\"x\":"}}]}}]}"#, + ), + make_sse( + "", + r#"{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"prompt_tokens_details":{"cached_tokens":3}}}"#, + ), + make_sse( + error_event_type, + r#"{"error":{"type":"server_error","code":"stream_interrupted","message":"synthetic failure","details":{"retryable":true}}}"#, + ), + make_sse("", "[DONE]"), + ]; + let (info, body) = extract_sse(&events); + let value = body.get().expect("received partial output must survive"); + let message = &value["choices"][0]["message"]; + assert_eq!(message["content"], "partial answer"); + assert_eq!(message["reasoning_content"], "first thought"); + assert_eq!(message["reasoning"], "step one"); + assert_eq!( + message["tool_calls"], + json!([ + {"id":"call_partial","type":"function","function":{"name":"lookup","arguments":"{\"city\":\"synthetic"}}, + {"id":"call_other","type":"function","function":{"name":"other","arguments":"{\"x\":"}} + ]) + ); + assert_eq!( + value["error"], + json!({ + "type": "server_error", + "code": "stream_interrupted", + "message": "synthetic failure", + "details": {"retryable": true} + }), + "event_type={error_event_type:?}" + ); + assert_eq!(info.response_id.as_deref(), Some("chatcmpl-partial")); + assert_eq!(info.model.as_deref(), Some("synthetic-model")); + assert_eq!(info.input_tokens, Some(10)); + assert_eq!(info.output_tokens, Some(5)); + assert_eq!(info.total_tokens, Some(15)); + assert_eq!(info.cache_read_input_tokens, Some(3)); + assert_eq!(value["usage"]["completion_tokens"], 5); + assert!(info.finish_reason.is_none()); + assert!(value["choices"][0]["finish_reason"].is_null()); + assert!(value.get("status").is_none()); + assert_eq!( + serde_json::from_str::(info.response_body.as_deref().unwrap()).unwrap(), + *value + ); + } + } + + #[test] + fn test_extract_sse_empty_and_unknown_objects_do_not_create_success_body() { + for event_type in ["", "message"] { + for payload in [ + "{}", + r#"{"unknown":"synthetic"}"#, + r#"{"choices":[]}"#, + r#"{"choices":[{}]}"#, + r#"{"choices":[{"delta":{}}]}"#, + r#"{"usage":{}}"#, + r#"{"error":null}"#, + r#"{"type":"provider.unknown","message":"synthetic notice"}"#, + ] { + let (info, body) = extract_sse(&[make_sse(event_type, payload)]); + assert!( + info.response_body.is_none(), + "event_type={event_type:?}, payload={payload}" + ); + assert!(body.get().is_none()); + assert!(info.response_id.is_none()); + assert!(info.model.is_none()); + assert!(info.finish_reason.is_none()); + } + } + } + + #[test] + fn test_extract_sse_done_and_malformed_payloads_do_not_create_body() { + for event_type in ["", "message"] { + let events = [ + make_sse(event_type, "[DONE]"), + make_sse(event_type, "not JSON"), + make_sse(event_type, "null"), + make_sse(event_type, "[]"), + make_sse(event_type, "42"), + ]; + let (info, body) = extract_sse(&events); + assert!(info.response_body.is_none()); + assert!(info.finish_reason.is_none()); + assert!(body.get().is_none()); + } + } + + #[test] + fn test_extract_sse_responses_named_events_cannot_supply_chat_or_error() { + // Specific Responses names are authoritative even if the payload + // contains fields that could otherwise look like Chat or an error. + for event_type in [ + "response.completed", + "response.failed", + "response.output_text.delta", + ] { + let (info, body) = extract_sse(&[make_sse( + event_type, + r#"{"type":"error","id":"resp-synthetic","model":"other-model","choices":[{"index":0,"delta":{"content":"wrong API"},"finish_reason":"stop"}],"usage":{"prompt_tokens":99},"error":{"code":"wrong_api","message":"synthetic failure"}}"#, + )]); + assert!(info.response_body.is_none(), "event_type={event_type}"); + assert!(body.get().is_none()); + assert!(info.response_id.is_none()); + assert!(info.model.is_none()); + assert!(info.finish_reason.is_none()); + assert!(info.input_tokens.is_none()); + } + } + + #[test] + fn test_extract_sse_error_does_not_replace_provider_finish_or_usage() { + for finish_reason in ["stop", "length", "tool_calls", "provider_custom"] { + for error_first in [false, true] { + let terminal = json!({ + "id": "chatcmpl-finished", + "model": "synthetic-model", + "choices": [{"index": 0, "delta": {"content": "received"}, "finish_reason": finish_reason}], + "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15, "prompt_tokens_details": {"cached_tokens": 3}} + }); + let error = make_sse( + "error", + r#"{"code":"server_error","message":"synthetic failure","param":null}"#, + ); + let terminal = make_sse("", &terminal.to_string()); + let mut events = if error_first { + vec![error, terminal] + } else { + vec![terminal, error] + }; + events.push(make_sse( + "", + r#"{"id":"chatcmpl-later","model":"later-model","choices":[],"usage":{"prompt_tokens":99,"completion_tokens":88,"total_tokens":187}}"#, + )); + let (info, body) = extract_sse(&events); + let value = body.get().expect("provider result must survive"); + assert_eq!(info.response_id.as_deref(), Some("chatcmpl-finished")); + assert_eq!(info.model.as_deref(), Some("synthetic-model")); + assert_eq!(info.finish_reason.as_deref(), Some(finish_reason)); + assert_eq!(info.input_tokens, Some(10)); + assert_eq!(info.output_tokens, Some(5)); + assert_eq!(info.total_tokens, Some(15)); + assert_eq!(info.cache_read_input_tokens, Some(3)); + assert_eq!(value["choices"][0]["message"]["content"], "received"); + assert_eq!(value["choices"][0]["finish_reason"], finish_reason); + assert_eq!( + value["error"], + json!({"code":"server_error","message":"synthetic failure","param":null}) + ); + assert!(value.get("status").is_none()); + } + } + } + + #[test] + fn test_extract_sse_initial_role_and_identity_are_retained() { + for event_type in ["", "message"] { + for (payload, response_id, model) in [ + ( + r#"{"choices":[{"index":0,"delta":{"role":"assistant"}}]}"#, + None, + None, + ), + ( + r#"{"id":"chatcmpl-metadata","model":"synthetic-model","choices":[]}"#, + Some("chatcmpl-metadata"), + Some("synthetic-model"), + ), + (r#"{"id":"chatcmpl-id"}"#, Some("chatcmpl-id"), None), + ( + r#"{"model":"synthetic-model"}"#, + None, + Some("synthetic-model"), + ), + ] { + let (info, body) = extract_sse(&[make_sse(event_type, payload)]); + assert!( + info.response_body.is_some(), + "event_type={event_type:?}, payload={payload}" + ); + assert!(body.get().is_some()); + assert_eq!(info.response_id.as_deref(), response_id); + assert_eq!(info.model.as_deref(), model); + assert!(info.finish_reason.is_none()); + } + } + } + + #[test] + fn test_extract_sse_usage_only_chunk_keeps_reported_counts() { + for event_type in ["", "message"] { + let (info, body) = extract_sse(&[make_sse( + event_type, + r#"{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15,"prompt_tokens_details":{"cached_tokens":3}}}"#, + )]); + assert_eq!(info.input_tokens, Some(10)); + assert_eq!(info.output_tokens, Some(5)); + assert_eq!(info.total_tokens, Some(15)); + assert_eq!(info.cache_read_input_tokens, Some(3)); + assert!(info.finish_reason.is_none()); + assert!(info.response_id.is_none()); + assert!(info.model.is_none()); + assert_eq!(body.get().unwrap()["usage"]["prompt_tokens"], 10); + } + } + #[test] fn test_synthetic_body_includes_usage() { let events = vec![ @@ -1065,8 +1454,16 @@ mod tests { }; let cache = ParsedJson::from_bytes(resp.body.clone()); let info = extract_response(&resp, &cache); - assert_eq!(info.input_tokens, Some(309), "should extract input_tokens from Anthropic-style usage"); - assert_eq!(info.output_tokens, Some(37), "should extract output_tokens from Anthropic-style usage"); + assert_eq!( + info.input_tokens, + Some(309), + "should extract input_tokens from Anthropic-style usage" + ); + assert_eq!( + info.output_tokens, + Some(37), + "should extract output_tokens from Anthropic-style usage" + ); } #[test] @@ -1103,8 +1500,16 @@ mod tests { }; let cache = ParsedJson::from_bytes(resp.body.clone()); let info = extract_response(&resp, &cache); - assert_eq!(info.input_tokens, Some(10), "OpenAI prompt_tokens must win over Anthropic input_tokens"); - assert_eq!(info.output_tokens, Some(5), "OpenAI completion_tokens must win over Anthropic output_tokens"); + assert_eq!( + info.input_tokens, + Some(10), + "OpenAI prompt_tokens must win over Anthropic input_tokens" + ); + assert_eq!( + info.output_tokens, + Some(5), + "OpenAI completion_tokens must win over Anthropic output_tokens" + ); } #[test] @@ -1125,8 +1530,16 @@ mod tests { ), ]; let (info, _body) = extract_sse(&events); - assert_eq!(info.input_tokens, Some(309), "should extract input_tokens from Anthropic-style usage in SSE"); - assert_eq!(info.output_tokens, Some(37), "should extract output_tokens from Anthropic-style usage in SSE"); + assert_eq!( + info.input_tokens, + Some(309), + "should extract input_tokens from Anthropic-style usage in SSE" + ); + assert_eq!( + info.output_tokens, + Some(37), + "should extract output_tokens from Anthropic-style usage in SSE" + ); } #[test] diff --git a/server/h-llm/src/wire_apis/openai/responses.rs b/server/h-llm/src/wire_apis/openai/responses.rs index 3fea20fa..c85bda1f 100644 --- a/server/h-llm/src/wire_apis/openai/responses.rs +++ b/server/h-llm/src/wire_apis/openai/responses.rs @@ -11,6 +11,7 @@ //! consumers always see the full output. use serde_json::Value; +use std::collections::HashMap; use h_protocol::model::{HttpRequestData, HttpResponseData, SseEventData}; @@ -138,6 +139,51 @@ fn extract_response(resp: &HttpResponseData, resp_body: &ParsedJson) -> Response } } +// Sparse indexes avoid allocating attacker-controlled output/content indexes. +#[derive(Default)] +struct StreamOutputItem { + value: Value, + parts: std::collections::BTreeMap<(&'static str, u64), Value>, + complete: bool, +} + +impl StreamOutputItem { + fn snapshot(value: Value, complete: bool) -> Self { + let mut item = Self { + value, + complete, + ..Self::default() + }; + for field in ["content", "summary"] { + if let Some(parts) = item.value.get(field).and_then(Value::as_array) { + for (index, part) in parts.iter().enumerate() { + if part.is_object() { + item.parts.insert((field, index as u64), part.clone()); + } else { + tracing::warn!(field, index, "ignoring malformed Responses content part"); + } + } + } + } + item + } + + fn into_value(mut self) -> Value { + for field in ["content", "summary"] { + let parts: Vec = self + .parts + .iter() + .filter(|((name, _), _)| *name == field) + .map(|(_, value)| value.clone()) + .collect(); + if !parts.is_empty() { + self.value[field] = Value::Array(parts); + } + } + self.value + } +} + fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { let mut model: Option = None; let mut finish_reason: Option = None; @@ -149,19 +195,28 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { // end for storage. The same `Value` is handed to `body` so downstream // readers get it without a String->Value round-trip. let mut response_value: Option = None; + let mut stream_error: Option = None; let mut response_id: Option = None; // Codex streams output items via response.output_item.done; the terminal // response.completed often carries an empty `output` array. Accumulate // here and graft into the final body below. - let mut output_items: Vec = Vec::new(); + let mut output_items: std::collections::BTreeMap = + std::collections::BTreeMap::new(); + let mut output_ids: HashMap = HashMap::new(); for event in events { - match event.event_type.as_str() { + let data: Value = match serde_json::from_str(&event.data) { + Ok(value) => value, + Err(_) => continue, + }; + // SSE permits a generic event name; Responses carries its type in JSON. + // An explicit SSE name remains authoritative when both are present. + let event_type = match event.event_type.as_str() { + "" | "message" => data.get("type").and_then(Value::as_str).unwrap_or(""), + explicit => explicit, + }; + match event_type { "response.created" => { - let data: Value = match serde_json::from_str(&event.data) { - Ok(v) => v, - Err(_) => continue, - }; if let Some(response) = data.get("response") { if response_id.is_none() { if let Some(id) = response.get("id").and_then(|v| v.as_str()) { @@ -175,20 +230,113 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { } } } - "response.output_item.done" => { - let data: Value = match serde_json::from_str(&event.data) { - Ok(v) => v, - Err(_) => continue, - }; - if let Some(item) = data.get("item") { - output_items.push(item.clone()); + "response.output_item.added" | "response.output_item.done" => { + if let Some(item) = data.get("item").filter(|value| value.is_object()) { + let item_id = item.get("id").and_then(Value::as_str).map(str::to_owned); + let index = data + .get("output_index") + .and_then(Value::as_u64) + .or_else(|| item_id.as_ref().and_then(|id| output_ids.get(id).copied())) + .unwrap_or_else(|| { + output_items + .last_key_value() + .map_or(0, |(index, _)| index.saturating_add(1)) + }); + if let Some(id) = item_id { + output_ids.insert(id, index); + } + output_items.insert( + index, + StreamOutputItem::snapshot(item.clone(), event_type.ends_with(".done")), + ); } } - "response.completed" => { - let data: Value = match serde_json::from_str(&event.data) { - Ok(v) => v, - Err(_) => continue, + "response.output_text.delta" + | "response.output_text.done" + | "response.reasoning_text.delta" + | "response.reasoning_text.done" + | "response.reasoning_summary_text.delta" + | "response.reasoning_summary_text.done" + | "response.function_call_arguments.delta" + | "response.function_call_arguments.done" + | "response.custom_tool_call_input.delta" + | "response.custom_tool_call_input.done" => { + let index = data + .get("output_index") + .and_then(Value::as_u64) + .unwrap_or(0); + let arguments = event_type.starts_with("response.function_call_arguments."); + let custom_input = event_type.starts_with("response.custom_tool_call_input."); + let reasoning = event_type.starts_with("response.reasoning_"); + let item = output_items.entry(index).or_insert_with(|| { + let value = if arguments { + serde_json::json!({"type":"function_call","arguments":""}) + } else if custom_input { + serde_json::json!({"type":"custom_tool_call","input":""}) + } else if reasoning { + serde_json::json!({"type":"reasoning"}) + } else { + serde_json::json!({"type":"message","role":"assistant"}) + }; + StreamOutputItem::snapshot(value, false) + }); + if item.complete { + continue; + } + if let Some(id) = data.get("item_id").and_then(Value::as_str) { + output_ids.insert(id.to_owned(), index); + item.value["id"] = Value::String(id.to_string()); + } + let done = event_type.ends_with(".done"); + let field = if arguments { + "arguments" + } else if custom_input { + "input" + } else { + "text" + }; + let Some(text) = data + .get(if done { field } else { "delta" }) + .and_then(Value::as_str) + else { + continue; + }; + let target = if arguments || custom_input { + &mut item.value + } else { + let summary = event_type.starts_with("response.reasoning_summary_text."); + let index = data + .get(if summary { + "summary_index" + } else { + "content_index" + }) + .and_then(Value::as_u64) + .unwrap_or(0); + let kind = if summary { + "summary_text" + } else if reasoning { + "reasoning_text" + } else { + "output_text" + }; + item.parts + .entry((if summary { "summary" } else { "content" }, index)) + .or_insert_with(|| serde_json::json!({"type":kind,"text":""})) }; + if done { + target[field] = Value::String(text.to_string()); + } else if let Some(Value::String(accumulated)) = target.get_mut(field) { + accumulated.push_str(text); + } else { + target[field] = Value::String(text.to_string()); + } + } + "response.completed" + | "response.failed" + | "response.incomplete" + | "response.cancelled" + | "response.done" => { if let Some(response) = data.get("response") { if let Some(id) = response.get("id").and_then(|v| v.as_str()) { response_id = Some(id.to_string()); @@ -218,28 +366,52 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { } } - // Graft accumulated items into the response object when - // the wire copy is missing or empty (codex behavior); - // otherwise preserve the wire copy verbatim. - let mut response_obj = response.clone(); - let needs_graft = response_obj - .get("output") - .and_then(|o| o.as_array()) - .map(|a| a.is_empty()) - .unwrap_or(true); - if needs_graft && !output_items.is_empty() { - if let Some(map) = response_obj.as_object_mut() { - map.insert("output".to_string(), Value::Array(output_items.clone())); - } - } - response_value = Some(response_obj); + response_value = Some(response.clone()); } } - // Anything else (including untyped Chat-style chunks) is not ours. + "error" => { + // Keep the complete event as fallback evidence, without + // assigning a response status or overriding a terminal body. + stream_error = Some(data.clone()); + } + // Unknown payloads are not Responses events. _ => {} } } + let output_items: Vec = output_items + .into_values() + .map(StreamOutputItem::into_value) + .collect(); + if let Some(response) = response_value.as_mut() { + // Some gateways send the final output exclusively in item events. + let needs_graft = response + .get("output") + .and_then(Value::as_array) + .is_none_or(Vec::is_empty); + if needs_graft && !output_items.is_empty() && response.is_object() { + response["output"] = Value::Array(output_items); + } + } else if !output_items.is_empty() || stream_error.is_some() { + // A partial snapshot preserves received data without inventing success. + let mut partial = serde_json::Map::new(); + partial.insert("output".into(), Value::Array(output_items)); + if let Some(error) = stream_error { + partial.insert("error".into(), error); + } + if let Some(id) = response_id.as_ref() { + partial.insert("id".into(), Value::String(id.clone())); + } + if let Some(name) = model.as_ref() { + partial.insert("model".into(), Value::String(name.clone())); + } + response_value = Some(Value::Object(partial)); + tracing::warn!( + events = events.len(), + "Responses stream missing terminal event; retaining received data" + ); + } + let response_body = response_value.as_ref().map(Value::to_string); let response_cache = ParsedJson::from_value(response_value); @@ -264,7 +436,8 @@ fn extract_sse(events: &[SseEventData]) -> (ResponseInfo, ParsedJson) { /// (e.g., `function_call`, `custom_tool_call`, `local_shell_call`, MCP /// variants) means the agent will execute a tool and re-POST → not terminal. /// `message` items count as the final answer; `reasoning` is ignored. -/// Return true iff at least one `message` is present and no `*_call` is. +/// Return true only for an observed `completed` status with at least one +/// `message` and no `*_call`. Partial snapshots never complete a turn. /// /// Used by both `CodexCliProfile` and `GenericProfile` (openai-responses /// branch) — the OpenAI Responses protocol always sets `status: "completed"` @@ -288,6 +461,10 @@ pub fn body_has_terminal_message_only(response_body: Option<&str>) -> bool { /// `Value`-input sibling of `body_has_terminal_message_only`. Used by /// `AgentProfile::is_turn_terminal` overrides on the parse-once hot path. pub fn body_has_terminal_message_only_value(resp: &Value) -> bool { + // Partial assembled output is useful evidence, not a completed agent turn. + if resp.get("status").and_then(Value::as_str) != Some("completed") { + return false; + } let Some(output) = resp.get("output").and_then(|o| o.as_array()) else { return false; }; @@ -680,7 +857,7 @@ mod terminal_helper_tests { #[test] fn terminal_when_output_only_has_message() { - let body = r#"{"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}]}"#; + let body = r#"{"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}]}"#; assert!(body_has_terminal_message_only(Some(body))); } @@ -715,8 +892,8 @@ mod terminal_helper_tests { #[cfg(test)] mod tests { use super::*; - use std::net::IpAddr; use h_protocol::net::FlowKey; + use std::net::IpAddr; fn make_sse(event_type: &str, data: &str) -> SseEventData { let ip: IpAddr = IpAddr::from([127, 0, 0, 1]); @@ -767,6 +944,420 @@ mod tests { assert_eq!(types, vec!["reasoning", "message"]); } + #[test] + fn test_generic_event_types_use_responses_payload_type() { + // Removing the payload-type fallback loses every field despite + // complete, valid Responses data being present on the wire. + for event_type in ["", "message"] { + let events = vec![ + make_sse( + event_type, + r#"{"type":"response.created","response":{"id":"resp_generic","model":"synthetic-model","status":"in_progress"}}"#, + ), + make_sse( + event_type, + r#"{"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"synthetic answer"}]}}"#, + ), + make_sse( + event_type, + r#"{"type":"response.completed","response":{"id":"resp_generic","model":"synthetic-model","status":"completed","output":[],"usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}}"#, + ), + ]; + let (info, body) = extract_sse(&events); + assert_eq!( + info.finish_reason.as_deref(), + Some("completed"), + "event_type={event_type:?}" + ); + assert_eq!(info.response_id.as_deref(), Some("resp_generic")); + assert_eq!(info.model.as_deref(), Some("synthetic-model")); + assert_eq!(info.input_tokens, Some(3)); + assert_eq!(info.output_tokens, Some(2)); + assert_eq!(info.total_tokens, Some(5)); + assert_eq!( + body.get().unwrap()["output"][0]["content"][0]["text"], + "synthetic answer" + ); + assert!(info.response_body.is_some()); + } + } + + #[test] + fn test_error_event_only_preserves_payload_without_inventing_status() { + let error = r#"{"type":"error","code":"server_error","message":"synthetic failure","param":null,"sequence_number":7}"#; + for event_type in ["error", "", "message"] { + let (info, body) = extract_sse(&[make_sse(event_type, error)]); + let value = body.get().expect("received error must survive extraction"); + assert_eq!( + value["error"], + serde_json::json!({ + "type":"error", "code":"server_error", "message":"synthetic failure", + "param":null, "sequence_number":7 + }) + ); + assert!(info.response_body.is_some()); + assert!(info.finish_reason.is_none()); + assert!(value.get("status").is_none()); + assert!(!body_has_terminal_message_only_value(value)); + } + } + + // @scenario LLM-STREAM-EVIDENCE-001 unit + #[test] + fn test_error_event_preserves_partial_output_and_identity() { + for event_type in ["error", "", "message"] { + let events = vec![ + make_sse( + "response.created", + r#"{"response":{"id":"resp_error","model":"synthetic-model","status":"in_progress"}}"#, + ), + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"content_index":0,"delta":"partial"}"#, + ), + make_sse( + event_type, + r#"{"type":"error","code":"server_error","message":"synthetic failure","param":null,"sequence_number":9}"#, + ), + ]; + let (info, body) = extract_sse(&events); + let value = body.get().expect("partial response must survive an error"); + assert_eq!(value["id"], "resp_error"); + assert_eq!(value["model"], "synthetic-model"); + assert_eq!(value["output"][0]["content"][0]["text"], "partial"); + assert_eq!( + value["error"], + serde_json::json!({ + "type":"error", "code":"server_error", "message":"synthetic failure", + "param":null, "sequence_number":9 + }) + ); + assert_eq!(info.response_id.as_deref(), Some("resp_error")); + assert_eq!(info.model.as_deref(), Some("synthetic-model")); + assert!(info.finish_reason.is_none()); + assert!(value.get("status").is_none()); + } + } + + #[test] + fn test_error_event_does_not_override_authoritative_terminal() { + for error_first in [false, true] { + let error = make_sse( + "error", + r#"{"type":"error","code":"server_error","message":"synthetic failure","sequence_number":1}"#, + ); + let terminal = make_sse( + "response.completed", + r#"{"response":{"id":"resp_success","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"complete"}]}]}}"#, + ); + let events = if error_first { + vec![error, terminal] + } else { + vec![terminal, error] + }; + let (info, body) = extract_sse(&events); + let value = body.get().unwrap(); + assert_eq!(info.finish_reason.as_deref(), Some("completed")); + assert_eq!(value["id"], "resp_success"); + assert_eq!(value["output"][0]["content"][0]["text"], "complete"); + assert!(value.get("error").is_none()); + } + } + + #[test] + fn test_unknown_error_like_payload_does_not_become_response() { + for event_type in ["provider.unknown", "", "message"] { + let (info, body) = extract_sse(&[make_sse( + event_type, + r#"{"type":"provider.unknown","code":"server_error","message":"synthetic failure"}"#, + )]); + assert!(info.response_body.is_none()); + assert!(info.finish_reason.is_none()); + assert!(body.get().is_none()); + } + } + + #[test] + fn test_failed_terminal_keeps_response_and_error() { + let events = vec![make_sse( + "response.failed", + r#"{"type":"response.failed","response":{"id":"resp_failed","model":"synthetic-model","status":"failed","output":[],"error":{"code":"server_error","message":"synthetic failure"}}}"#, + )]; + let (info, body) = extract_sse(&events); + assert_eq!(info.finish_reason.as_deref(), Some("failed")); + assert_eq!(info.response_id.as_deref(), Some("resp_failed")); + assert_eq!(body.get().unwrap()["error"]["code"], "server_error"); + assert!(info.response_body.is_some()); + } + + #[test] + fn test_incomplete_terminal_keeps_response_and_usage() { + let events = vec![make_sse( + "response.incomplete", + r#"{"type":"response.incomplete","response":{"id":"resp_incomplete","model":"synthetic-model","status":"incomplete","output":[],"incomplete_details":{"reason":"max_output_tokens"},"usage":{"input_tokens":3,"output_tokens":2,"total_tokens":5}}}"#, + )]; + let (info, body) = extract_sse(&events); + assert_eq!(info.finish_reason.as_deref(), Some("incomplete")); + assert_eq!(info.output_tokens, Some(2)); + assert_eq!( + body.get().unwrap()["incomplete_details"]["reason"], + "max_output_tokens" + ); + assert!(info.response_body.is_some()); + } + + #[test] + fn test_specific_event_type_takes_precedence_over_payload_type() { + let events = vec![make_sse( + "response.completed", + r#"{"type":"response.failed","response":{"id":"resp_typed","status":"completed","output":[]}}"#, + )]; + let (info, _) = extract_sse(&events); + assert_eq!(info.finish_reason.as_deref(), Some("completed")); + assert!(info.response_body.is_some()); + } + + #[test] + fn test_done_after_terminal_does_not_discard_response() { + let events = vec![ + make_sse( + "response.completed", + r#"{"response":{"id":"resp_done","status":"completed","output":[]}}"#, + ), + make_sse("", "[DONE]"), + ]; + let (info, _) = extract_sse(&events); + assert_eq!(info.finish_reason.as_deref(), Some("completed")); + assert_eq!(info.response_id.as_deref(), Some("resp_done")); + assert!(info.response_body.is_some()); + } + + // @scenario LLM-STREAM-EVIDENCE-001 unit + #[test] + fn test_done_without_terminal_does_not_invent_completion() { + let events = vec![ + make_sse( + "response.output_item.done", + r#"{"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"partial"}]}}"#, + ), + make_sse("", "[DONE]"), + ]; + let (info, body) = extract_sse(&events); + assert!(info.finish_reason.is_none()); + assert!(info.response_body.is_some()); + assert!(body.get().unwrap().get("status").is_none()); + } + + #[test] + fn test_done_and_cancelled_terminal_keep_response() { + for (event_type, status) in [ + ("response.done", "completed"), + ("response.cancelled", "cancelled"), + ] { + let data = + serde_json::json!({"response":{"id":"resp_terminal","status":status,"output":[]}}); + let (info, body) = extract_sse(&[make_sse(event_type, &data.to_string())]); + assert_eq!(info.finish_reason.as_deref(), Some(status)); + assert_eq!(body.get().unwrap()["id"], "resp_terminal"); + } + } + + #[test] + fn test_partial_output_is_retained_without_fabricating_finish() { + let events = vec![make_sse( + "response.output_item.done", + r#"{"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"partial answer"}]}}"#, + )]; + let (info, body) = extract_sse(&events); + assert!(info.finish_reason.is_none()); + let value = body + .get() + .expect("received output must survive a missing terminal"); + assert_eq!(value["output"][0]["content"][0]["text"], "partial answer"); + assert!( + value.get("status").is_none(), + "capture must not invent provider completion" + ); + } + + #[test] + fn test_partial_message_never_closes_a_turn() { + let events = vec![make_sse( + "response.output_item.done", + r#"{"item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"partial"}]}}"#, + )]; + let (_, body) = extract_sse(&events); + assert!( + !body_has_terminal_message_only_value(body.get().unwrap()), + "received partial output is not evidence of completion" + ); + assert!(!body_has_terminal_message_only(Some( + r#"{"status":"in_progress","output":[{"type":"message"}]}"# + ))); + } + + #[test] + fn test_delta_only_output_survives_without_terminal_or_item_done() { + let events = vec![ + make_sse( + "response.output_item.added", + r#"{"output_index":0,"item":{"id":"msg_partial","type":"message","role":"assistant","content":[]}}"#, + ), + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"content_index":0,"delta":"你"}"#, + ), + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"content_index":0,"delta":"好"}"#, + ), + make_sse( + "response.output_item.added", + r#"{"output_index":1,"item":{"id":"call_partial","type":"function_call","name":"f","arguments":""}}"#, + ), + make_sse( + "response.function_call_arguments.delta", + r#"{"output_index":1,"delta":"{\"x\":"}"#, + ), + ]; + let (info, body) = extract_sse(&events); + let body = body + .get() + .expect("already received deltas must survive missing terminal"); + assert_eq!(body["output"][0]["content"][0]["text"], "你好"); + assert_eq!(body["output"][1]["arguments"], "{\"x\":"); + assert!(info.finish_reason.is_none()); + assert!(body.get("status").is_none()); + } + + #[test] + fn test_custom_tool_input_survives_missing_terminal_and_item_snapshot() { + for added in [false, true] { + let mut events = vec![]; + if added { + events.push(make_sse("response.output_item.added", r#"{"output_index":0,"item":{"id":"tool","type":"custom_tool_call","input":""}}"#)); + } + events.push(make_sse( + "response.custom_tool_call_input.delta", + r#"{"output_index":0,"item_id":"tool","delta":"已收到工具输入"}"#, + )); + let (info, body) = extract_sse(&events); + assert_eq!( + body.get().expect("captured tool input must survive")["output"][0]["input"], + "已收到工具输入" + ); + assert!(info.finish_reason.is_none()); + events.push(make_sse( + "response.custom_tool_call_input.done", + r#"{"output_index":0,"item_id":"tool","input":"完整输入"}"#, + )); + let (_, body) = extract_sse(&events); + let item = &body.get().unwrap()["output"][0]; + assert_eq!(item["type"], "custom_tool_call"); + assert_eq!(item["input"], "完整输入"); + assert!(body.get().unwrap().get("status").is_none()); + } + } + + #[test] + fn test_malformed_content_parts_cannot_panic_on_delta() { + for bad in [ + serde_json::json!("bad"), + serde_json::json!(3), + serde_json::json!([]), + Value::Null, + ] { + let mut item = serde_json::json!({"type":"message","content":[]}); + item["content"] = serde_json::json!([bad]); + let events = vec![ + make_sse( + "response.output_item.added", + &serde_json::json!({"output_index":0,"item":item}).to_string(), + ), + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"content_index":0,"delta":"recovered"}"#, + ), + ]; + let (_, body) = extract_sse(&events); + assert_eq!( + body.get().unwrap()["output"][0]["content"][0]["text"], + "recovered" + ); + } + } + + #[test] + fn test_delta_item_id_matches_done_without_index() { + let events = vec![ + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"item_id":"m","content_index":0,"delta":"partial"}"#, + ), + make_sse( + "response.output_item.done", + r#"{"item":{"id":"m","type":"message","content":[{"type":"output_text","text":"final"}]}}"#, + ), + ]; + let (_, body) = extract_sse(&events); + let output = body.get().unwrap()["output"].as_array().unwrap(); + assert_eq!( + output.len(), + 1, + "delta skeleton and final item have one identity" + ); + assert_eq!(output[0]["content"][0]["text"], "final"); + } + + #[test] + fn test_missing_output_index_matches_item_ids_before_appending() { + let events = vec![ + make_sse( + "response.output_item.added", + r#"{"item":{"id":"a","type":"message","content":[]}}"#, + ), + make_sse( + "response.output_item.added", + r#"{"item":{"id":"b","type":"function_call","arguments":""}}"#, + ), + make_sse( + "response.output_item.done", + r#"{"item":{"id":"a","type":"message","content":[{"type":"output_text","text":"final"}]}}"#, + ), + ]; + let (_, body) = extract_sse(&events); + let output = body.get().unwrap()["output"].as_array().unwrap(); + assert_eq!(output.len(), 2); + assert_eq!(output[0]["content"][0]["text"], "final"); + assert_eq!(output[1]["id"], "b"); + } + + #[test] + fn test_done_item_replaces_deltas_without_duplicate_output() { + let events = vec![ + make_sse( + "response.output_item.added", + r#"{"output_index":0,"item":{"id":"msg","type":"message","role":"assistant","content":[]}}"#, + ), + make_sse( + "response.output_text.delta", + r#"{"output_index":0,"content_index":0,"delta":"partial"}"#, + ), + make_sse( + "response.output_item.done", + r#"{"output_index":0,"item":{"id":"msg","type":"message","role":"assistant","content":[{"type":"output_text","text":"final"}]}}"#, + ), + make_sse( + "response.completed", + r#"{"response":{"status":"completed","output":[]}}"#, + ), + ]; + let (_, body) = extract_sse(&events); + let output = body.get().unwrap()["output"].as_array().unwrap(); + assert_eq!(output.len(), 1); + assert_eq!(output[0]["content"][0]["text"], "final"); + } + #[test] fn test_preserves_nonempty_response_output() { // If response.completed already carries output (older/alternative diff --git a/server/h-protocol/src/http.rs b/server/h-protocol/src/http.rs index 7b3a4732..cf9055a0 100644 --- a/server/h-protocol/src/http.rs +++ b/server/h-protocol/src/http.rs @@ -114,9 +114,10 @@ struct BodyReader { decoded_body: BytesMut, /// When true, the reader still emits each `ChunkDecoded` so callers (the /// SSE parser) can consume chunks incrementally, but stops accumulating - /// them into `decoded_body` and returns empty bytes from `Complete` and - /// `finish`. Used for SSE responses whose raw body is never read by any - /// downstream stage (LlmProcessor rebuilds response_body from SSE events). + /// them into `decoded_body`. `Complete` and `finish` return only trailing + /// bytes that were not emitted incrementally. Used for SSE responses whose + /// raw body is never read by any downstream stage (LlmProcessor rebuilds + /// response_body from SSE events). skip_accumulation: bool, /// `Content-Encoding` decompressor. `None` for the common uncompressed case, /// where the body passes through byte-for-byte unchanged. @@ -264,12 +265,12 @@ impl BodyReader { let _ = buf.split_to(total); // Flush any decompressor remainder into the body. let tail = self.flush_decompressor(); - if !self.skip_accumulation && !tail.is_empty() { - self.decoded_body.extend_from_slice(&tail); - } let body = if self.skip_accumulation { - Bytes::new() + // Previously streamed bytes are not retained; + // only this unsent decoder tail is returned. + tail } else { + self.decoded_body.extend_from_slice(&tail); self.decoded_body.split().freeze() }; return ReadResult::Complete(body); @@ -297,70 +298,75 @@ impl BodyReader { ReadResult::ChunkDecoded(chunk_data) } - /// Flush remaining data as body on connection close. + /// Flush remaining payload on connection close. For streaming SSE this + /// returns only bytes not previously emitted through `ChunkDecoded`. fn finish(&mut self, buf: &mut BytesMut) -> Bytes { - match self.framing { - BodyFraming::NoBody => Bytes::new(), - BodyFraming::ContentLength(_) => { - let raw = buf.split(); - if self.skip_accumulation { - Bytes::new() - } else { - let mut body = self.decode_payload(&raw).to_vec(); - body.extend_from_slice(&self.flush_decompressor()); - Bytes::from(body) - } - } - BodyFraming::Chunked | BodyFraming::CloseDelimited => { - if self.skip_accumulation { - buf.clear(); - Bytes::new() - } else { - if !buf.is_empty() { - let raw = buf.split(); - let data = self.decode_payload(&raw); - self.decoded_body.extend_from_slice(&data); - } - let tail = self.flush_decompressor(); - if !tail.is_empty() { - self.decoded_body.extend_from_slice(&tail); + let raw = match self.framing { + BodyFraming::NoBody => return Bytes::new(), + BodyFraming::ContentLength(_) | BodyFraming::CloseDelimited => buf.split(), + BodyFraming::Chunked => { + // `read` already consumed all complete chunks. At EOF the + // remaining chunk may lack payload bytes or its trailing CRLF; + // decode only the captured payload, never size/trailer lines. + let mut remaining = buf.split(); + if let Some(line_end) = find_crlf(&remaining) { + let size = std::str::from_utf8(&remaining[..line_end]) + .ok() + .and_then(|line| line.split(';').next()) + .and_then(|size| usize::from_str_radix(size.trim(), 16).ok()); + if let Some(size) = size { + let _ = remaining.split_to(line_end + 2); + remaining.truncate(remaining.len().min(size)); + remaining + } else { + BytesMut::new() } - self.decoded_body.split().freeze() + } else { + BytesMut::new() } } + }; + let data = self.decode_payload(&raw); + let tail = self.flush_decompressor(); + if self.skip_accumulation { + let mut pending = BytesMut::from(&data[..]); + pending.extend_from_slice(&tail); + pending.freeze() + } else { + self.decoded_body.extend_from_slice(&data); + self.decoded_body.extend_from_slice(&tail); + self.decoded_body.split().freeze() } } - /// Whether body data was fed incrementally via `ChunkDecoded`. - fn was_incremental(&self) -> bool { - matches!( - self.framing, - BodyFraming::Chunked | BodyFraming::CloseDelimited - ) - } - fn is_no_body(&self) -> bool { self.framing == BodyFraming::NoBody } } -/// Parses SSE events from a stream of text data. +/// Parses SSE events from a byte stream. UTF-8 code points may cross input chunks. struct SseParser { - residual: String, + residual: BytesMut, + /// A CR already ended the preceding line; swallow a following LF, even + /// when the CRLF pair spans input chunks. + skip_lf: bool, } impl SseParser { fn new() -> Self { Self { - residual: String::new(), + residual: BytesMut::new(), + skip_lf: false, } } fn reset(&mut self) { self.residual.clear(); + self.skip_lf = false; } - /// Feed a chunk of text. Complete SSE events are emitted to `output`. + /// Text convenience wrapper for existing parser tests. + #[cfg(test)] fn push( &mut self, text: &str, @@ -370,27 +376,75 @@ impl SseParser { timestamp: i64, output: &mut Vec, ) { - self.residual.push_str(text); + self.push_bytes( + text.as_bytes(), + flow_key, + client_addr, + server_addr, + timestamp, + output, + ); + } - loop { - // SSE events are separated by blank lines. - let (sep_pos, skip) = if let Some(pos) = self.residual.find("\r\n\r\n") { - (pos, 4) - } else if let Some(pos) = self.residual.find("\n\n") { - (pos, 2) - } else { - break; + /// Buffer bytes until a complete SSE frame can be decoded independently. + fn push_bytes( + &mut self, + bytes: &[u8], + flow_key: &FlowKey, + client_addr: (IpAddr, u16), + server_addr: (IpAddr, u16), + timestamp: i64, + output: &mut Vec, + ) { + // Normalize line endings while scanning only the newly arrived bytes. + // A frame stays bytes until an empty line ends it, so split UTF-8 code + // points and invalid frames retain the same independent handling. + let mut start = 0; + for (pos, &byte) in bytes.iter().enumerate() { + if self.skip_lf { + self.skip_lf = false; + if byte == b'\n' { + start = pos + 1; + continue; + } + } + if byte != b'\r' && byte != b'\n' { + continue; + } + self.residual.extend_from_slice(&bytes[start..pos]); + start = pos + 1; + self.skip_lf = byte == b'\r'; + if !self.residual.is_empty() && self.residual.last() != Some(&b'\n') { + self.residual.extend_from_slice(b"\n"); + continue; + } + let frame = self.residual.split(); + let Some(text) = Self::decode_frame(&frame) else { + continue; }; - - let event_text = self.residual[..sep_pos].to_string(); - self.residual = self.residual[sep_pos + skip..].to_string(); - if let Some(evt) = - Self::parse_event(&event_text, flow_key, client_addr, server_addr, timestamp) + Self::parse_event(text, flow_key, client_addr, server_addr, timestamp) { output.push(evt); } } + self.residual.extend_from_slice(&bytes[start..]); + } + + fn decode_frame(bytes: &[u8]) -> Option<&str> { + match std::str::from_utf8(bytes) { + Ok(text) => Some(text), + Err(error) => { + // Report encoding loss without logging captured payloads. Only + // this frame is discarded; subsequent frames remain parseable. + tracing::warn!( + frame_bytes = bytes.len(), + valid_up_to = error.valid_up_to(), + "discarding SSE frame with invalid UTF-8" + ); + None + } + } } /// Flush any remaining residual as a final event. @@ -403,7 +457,11 @@ impl SseParser { output: &mut Vec, ) { let residual = std::mem::take(&mut self.residual); - let trimmed = residual.trim(); + self.skip_lf = false; + let Some(text) = Self::decode_frame(&residual) else { + return; + }; + let trimmed = text.trim(); if trimmed.is_empty() { return; } @@ -559,6 +617,9 @@ impl HttpParser { timestamp_us: self.pending_req_timestamp, process: None, })); + // A split-out chunked body owns its allocation now; + // do not keep the empty reader view alive while idle. + self.body_reader = BodyReader::new(); self.state = ParserState::WaitingForResponse; break; } @@ -607,33 +668,27 @@ impl HttpParser { match self.body_reader.read(server_buf) { ReadResult::ChunkDecoded(chunk) => { if self.pending_resp_is_sse { - if let Ok(text) = std::str::from_utf8(&chunk) { - self.sse_parser.push( - text, - flow_key, - client_addr, - server_addr, - server_last_ts, - output, - ); - } + self.sse_parser.push_bytes( + &chunk, + flow_key, + client_addr, + server_addr, + server_last_ts, + output, + ); } continue; } ReadResult::Complete(body) => { if self.pending_resp_is_sse { - if !self.body_reader.was_incremental() { - if let Ok(text) = std::str::from_utf8(&body) { - self.sse_parser.push( - text, - flow_key, - client_addr, - server_addr, - server_last_ts, - output, - ); - } - } + self.sse_parser.push_bytes( + &body, + flow_key, + client_addr, + server_addr, + server_last_ts, + output, + ); self.sse_parser.flush( flow_key, client_addr, @@ -663,6 +718,7 @@ impl HttpParser { complete_timestamp_us: server_last_ts, process: None, })); + self.body_reader = BodyReader::new(); self.state = ParserState::WaitingForRequest; break; } @@ -690,18 +746,14 @@ impl HttpParser { } let body = self.body_reader.finish(server_buf); if self.pending_resp_is_sse { - if !self.body_reader.was_incremental() { - if let Ok(text) = std::str::from_utf8(&body) { - self.sse_parser.push( - text, - flow_key, - client_addr, - server_addr, - server_last_ts, - output, - ); - } - } + self.sse_parser.push_bytes( + &body, + flow_key, + client_addr, + server_addr, + server_last_ts, + output, + ); self.sse_parser .flush(flow_key, client_addr, server_addr, server_last_ts, output); } @@ -722,6 +774,7 @@ impl HttpParser { complete_timestamp_us: server_last_ts, process: None, })); + self.body_reader = BodyReader::new(); self.state = ParserState::WaitingForRequest; } @@ -848,6 +901,295 @@ mod tests { (fk, ca, sa) } + fn parse_sse_fragments(fragments: &[&[u8]], chunked: bool) -> Vec { + let (fk, ca, sa) = test_flow(); + let mut parser = HttpParser::new(); + let mut client_buf = BytesMut::from("GET /stream HTTP/1.1\r\nHost: localhost\r\n\r\n"); + let mut server_buf = + BytesMut::from("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"); + if chunked { + server_buf.extend_from_slice(b"Transfer-Encoding: chunked\r\n"); + } + server_buf.extend_from_slice(b"\r\n"); + let mut output = Vec::new(); + for fragment in fragments { + if chunked { + server_buf.extend_from_slice(format!("{:x}\r\n", fragment.len()).as_bytes()); + } + server_buf.extend_from_slice(fragment); + if chunked { + server_buf.extend_from_slice(b"\r\n"); + } + assert_eq!( + parser.parse( + &mut client_buf, + &mut server_buf, + &fk, + ca, + sa, + 0, + 1, + 2, + &mut output + ), + ParseResult::Ok, + ); + } + if chunked { + server_buf.extend_from_slice(b"0\r\n\r\n"); + assert_eq!( + parser.parse( + &mut client_buf, + &mut server_buf, + &fk, + ca, + sa, + 0, + 1, + 2, + &mut output + ), + ParseResult::Ok, + ); + } else { + parser.finish_response(&mut server_buf, &fk, ca, sa, 2, &mut output); + } + output + } + + fn sse_fields(output: &[HttpParseEvent]) -> Vec<(&str, &str)> { + output + .iter() + .filter_map(|event| match event { + HttpParseEvent::SseEvent(event) => { + Some((event.event_type.as_str(), event.data.as_str())) + } + _ => None, + }) + .collect() + } + + #[test] + fn test_completed_chunked_messages_release_reader_allocation() { + let (fk, ca, sa) = test_flow(); + let body_len = 2 * 1024 * 1024 + 17; + for request_body in [true, false] { + let mut parser = HttpParser::new(); + let mut chunked = BytesMut::from(if request_body { + "POST /large HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" + } else { + "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n" + }); + chunked.extend_from_slice(format!("{body_len:x}\r\n").as_bytes()); + chunked.resize(chunked.len() + body_len, b'x'); + chunked.extend_from_slice(b"\r\n0\r\n\r\n"); + let (mut client_buf, mut server_buf) = if request_body { + (chunked, BytesMut::new()) + } else { + (BytesMut::from("GET /large HTTP/1.1\r\n\r\n"), chunked) + }; + let mut output = Vec::new(); + assert_eq!( + parser.parse( + &mut client_buf, + &mut server_buf, + &fk, + ca, + sa, + 0, + 1, + 2, + &mut output + ), + ParseResult::Ok + ); + let body = output + .iter() + .find_map(|event| match event { + HttpParseEvent::HttpRequest(request) if request_body => Some(&request.body), + HttpParseEvent::HttpResponse(response) if !request_body => Some(&response.body), + _ => None, + }) + .expect("complete message body handed downstream"); + assert_eq!(body.len(), body_len); + assert!(body.iter().all(|&byte| byte == b'x')); + drop(output); + assert!(parser.body_reader.decoded_body.is_empty()); + assert!(!parser.body_reader.decoded_body.try_reclaim(body_len), "completed chunked message leaves a body-sized allocation in reader: request_body={request_body}"); + } + } + + // @scenario PROTO-STREAM-INTEGRITY-001 unit + #[test] + fn test_sse_utf8_survives_every_http_chunk_and_tcp_split() { + for newline in ["\n", "\r\n"] { + let body = format!( + "event: delta{newline}data: 中文🙂{newline}data: second{newline}{newline}event: done{newline}data: [DONE]{newline}{newline}" + ); + for chunked in [false, true] { + for split in 1..body.len() { + let output = parse_sse_fragments( + &[&body.as_bytes()[..split], &body.as_bytes()[split..]], + chunked, + ); + assert_eq!( + sse_fields(&output), + vec![("delta", "中文🙂\nsecond"), ("done", "[DONE]")], + "split={split}, chunked={chunked}, newline={newline:?}", + ); + assert_eq!( + output + .iter() + .filter(|e| matches!(e, HttpParseEvent::HttpResponse(_))) + .count(), + 1 + ); + } + } + } + } + + #[test] + fn test_sse_invalid_utf8_drops_only_bad_frame_then_recovers() { + let body = b"data: before\n\ndata: \xff\n\ndata: after\n\n"; + for chunked in [false, true] { + let output = parse_sse_fragments(&[body], chunked); + assert_eq!(sse_fields(&output), vec![("", "before"), ("", "after")]); + let output = parse_sse_fragments(&[b"data: \xff", b"\n\ndata: recovered\n\n"], chunked); + assert_eq!(sse_fields(&output), vec![("", "recovered")]); + } + } + + #[test] + fn test_sse_mixed_newlines_preserve_frame_order() { + let output = parse_sse_fragments(&[b"data: first\n\ndata: second\r\n\r\n"], true); + assert_eq!(sse_fields(&output), vec![("", "first"), ("", "second")]); + } + + #[test] + fn test_sse_all_line_endings_bytewise_preserve_frames() { + let (fk, ca, sa) = test_flow(); + // Every supported line ending, including different endings for the + // data line and the empty line. CR followed by LF is one CRLF ending. + for line_end in ["\r", "\n", "\r\n"] { + for boundary in [ + "\r\r", "\n\n", "\r\n\r\n", "\n\r\n", "\r\n\n", "\n\r", "\r\n\r", + ] { + let body = format!("event: delta{line_end}data: 中文🙂{line_end}data: second{boundary}data: two{boundary}"); + for bytewise in [false, true] { + let mut parser = SseParser::new(); + let mut output = Vec::new(); + let width = if bytewise { 1 } else { body.len() }; + for bytes in body.as_bytes().chunks(width) { + parser.push_bytes(bytes, &fk, ca, sa, 7, &mut output); + } + // Complete frames must be visible before connection EOF. + assert_eq!( + sse_fields(&output), + vec![("delta", "中文🙂\nsecond"), ("", "two")], + "line_end={line_end:?}, boundary={boundary:?}, bytewise={bytewise}" + ); + parser.flush(&fk, ca, sa, 8, &mut output); + assert_eq!(output.len(), 2, "flush cannot duplicate a CRLF-split event"); + } + } + } + } + + #[test] + fn test_sse_content_length_eof_recovers_received_frames() { + let (fk, ca, sa) = test_flow(); + let mut parser = HttpParser::new(); + let mut client_buf = BytesMut::from("GET /stream HTTP/1.1\r\n\r\n"); + let mut server_buf = BytesMut::from("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: 200\r\n\r\ndata: first\n\ndata: 中文🙂\n\n"); + let mut output = Vec::new(); + assert_eq!( + parser.parse( + &mut client_buf, + &mut server_buf, + &fk, + ca, + sa, + 0, + 1, + 2, + &mut output + ), + ParseResult::Ok + ); + // FIN and capture EOF both use finish_response while Content-Length + // remains unmet. Only actually received frames may be recovered. + parser.finish_response(&mut server_buf, &fk, ca, sa, 2, &mut output); + assert_eq!(sse_fields(&output), vec![("", "first"), ("", "中文🙂")]); + let responses: Vec<_> = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert!(responses[0].body.is_empty()); + assert!(server_buf.is_empty()); + let event_count = output.len(); + parser.finish_response(&mut server_buf, &fk, ca, sa, 3, &mut output); + assert_eq!(output.len(), event_count); + } + + // @scenario PROTO-STREAM-INTEGRITY-001 unit + #[test] + fn test_sse_gzip_chunked_eof_recovers_buffered_payload_without_chunk_crlf() { + use flate2::write::GzEncoder; + use flate2::Compression; + let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); + encoder.write_all(b"data: first\n\n").unwrap(); + encoder.flush().unwrap(); + let split = encoder.get_ref().len(); + encoder + .write_all("data: tail 中文🙂\n\n".as_bytes()) + .unwrap(); + let gzip = encoder.finish().unwrap(); + let (fk, ca, sa) = test_flow(); + let mut parser = HttpParser::new(); + let mut client_buf = BytesMut::from("GET /stream HTTP/1.1\r\n\r\n"); + let mut server_buf = BytesMut::from("HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\nContent-Encoding: gzip\r\n\r\n"); + server_buf.extend_from_slice(format!("{:x}\r\n", split).as_bytes()); + server_buf.extend_from_slice(&gzip[..split]); + server_buf.extend_from_slice(format!("\r\n{:x}\r\n", gzip.len() - split).as_bytes()); + server_buf.extend_from_slice(&gzip[split..]); + // EOF before the last chunk's trailing CRLF: every compressed payload + // byte is present and the previous chunk was already streamed out. + let mut output = Vec::new(); + assert_eq!( + parser.parse( + &mut client_buf, + &mut server_buf, + &fk, + ca, + sa, + 0, + 1, + 2, + &mut output + ), + ParseResult::Ok + ); + assert_eq!(sse_fields(&output), vec![("", "first")]); + parser.finish_response(&mut server_buf, &fk, ca, sa, 2, &mut output); + assert_eq!( + sse_fields(&output), + vec![("", "first"), ("", "tail 中文🙂")] + ); + assert_eq!( + output + .iter() + .filter(|event| matches!(event, HttpParseEvent::HttpResponse(_))) + .count(), + 1 + ); + assert!(server_buf.is_empty()); + } + #[test] fn body_reader_gunzips_content_length_gzip() { use flate2::write::GzEncoder; diff --git a/server/h-protocol/src/stage.rs b/server/h-protocol/src/stage.rs index 215993a4..9f339f4f 100644 --- a/server/h-protocol/src/stage.rs +++ b/server/h-protocol/src/stage.rs @@ -140,7 +140,15 @@ pub fn spawn_protocol_stage( let reason = 'main: loop { let input = match wrx.recv().await { Some(x) => x, - None => break 'main "upstream_eof", + None => { + for event in worker.finish() { + if event_tx.send(event).await.is_err() { + break 'main "downstream_closed"; + } + } + flow_gauge.store(0, Ordering::Relaxed); + break 'main "upstream_eof"; + } }; for event in worker.process(input) { if event_tx.send(event).await.is_err() { diff --git a/server/h-protocol/src/tcp.rs b/server/h-protocol/src/tcp.rs index f29923dc..e4df9ab2 100644 --- a/server/h-protocol/src/tcp.rs +++ b/server/h-protocol/src/tcp.rs @@ -45,9 +45,15 @@ enum ClientSide { struct DirState { /// Reassembled in-order bytes pending HTTP parse. buf: BytesMut, + /// Remembers a large backing allocation even after splitting narrows the + /// visible capacity. Cleared only when that backing is detached/discarded. + large_backing: bool, /// Next expected sequence number; `None` until we observe SYN or the /// first data packet (mid-stream sync). next_seq: Option, + /// Sequence immediately after this direction's final payload. FIN is only + /// effective once all preceding bytes have been reassembled. + fin_seq: Option, /// Timestamp of the most recent data packet in this direction. Used as /// the stamping time for HTTP requests/responses at parse time — on /// keep-alive connections the connection's first-packet time is not a @@ -56,9 +62,9 @@ struct DirState { /// Out-of-order segment buffer. Lazily allocated: stays `None` for any /// flow that never sees an OOO arrival, so the in-order hot path costs /// one `Option` discriminant test. Capped at `OOO_CAP_SEGMENTS`; when - /// full we evict the lowest-seq entry. Live span is bounded by the cap - /// (≪ 2³¹ bytes), so `BTreeMap`'s natural u32 ordering matches the - /// wraparound-aware logical ordering used in `drain_ooo`. + /// full we retain the entries closest to `next_seq`, so filling the first + /// gap can still advance reassembly. Sequence comparisons use wrapping + /// offsets: natural u32 ordering is wrong when a stream crosses zero. ooo: Option>, } @@ -66,7 +72,9 @@ impl DirState { fn new() -> Self { Self { buf: BytesMut::new(), + large_backing: false, next_seq: None, + fin_seq: None, last_data_ts: 0, ooo: None, } @@ -78,8 +86,35 @@ impl DirState { /// `next_seq` and `last_data_ts` are not touched here — callers manage /// them per resync semantics. fn discard_buffers(&mut self) { - self.buf.clear(); + self.buf = BytesMut::new(); + self.large_backing = false; self.ooo = None; + self.fin_seq = None; + } + + /// Detach a small tail from a formerly large allocation. Sampling before + /// parse and remembering earlier calls catches narrowed shared views too. + fn reclaim_parsed_buffer(&mut self, previous_capacity: usize) { + const LARGE_CAPACITY: usize = 1024 * 1024; + const SMALL_TAIL: usize = 64 * 1024; + self.large_backing |= previous_capacity >= LARGE_CAPACITY; + if self.large_backing && self.buf.len() <= SMALL_TAIL { + self.buf = if self.buf.is_empty() { + BytesMut::new() + } else { + BytesMut::from(self.buf.as_ref()) + }; + self.large_backing = false; + } + } + + fn fin_received(&self) -> bool { + self.fin_seq.is_some_and(|fin_seq| { + // A FIN observed before any payload is not proof that earlier + // bytes have arrived. Wait for a sequence baseline or cleanup. + self.next_seq + .is_some_and(|next| next.wrapping_sub(fin_seq) as i32 >= 0) + }) } } @@ -227,15 +262,6 @@ impl TcpFlow { return false; } - // FIN handling. - if pkt.has_fin() { - self.state = match self.state { - TcpState::Closing => TcpState::Closed, - _ => TcpState::Closing, - }; - // FIN consumes one sequence number; process any remaining payload below. - } - // If we haven't seen a SYN, transition to Established on first data. if (self.state == TcpState::Init || self.state == TcpState::SynSent) && !pkt.payload.is_empty() @@ -320,7 +346,16 @@ impl TcpFlow { (self.client_side, pkt.direction), (ClientSide::AtoB, Direction::AtoB) | (ClientSide::BtoA, Direction::BtoA) ); + // A request-looking retransmission is still old TCP data; + // it must reach append_payload's deduplication before resync. + let starts_new_data = self + .dir_mut(pkt.direction) + .next_seq + .map_or(true, |expected| { + pkt.tcp_seq.wrapping_sub(expected) as i32 >= 0 + }); if is_client + && starts_new_data && self.http_parser.is_waiting_for_response() && looks_like_http_request(&pkt.payload) { @@ -373,8 +408,26 @@ impl TcpFlow { } } - // Flush pending response on connection close. - if self.state == TcpState::Closing || self.state == TcpState::Closed { + if pkt.has_fin() { + let dir = self.dir_mut(pkt.direction); + // Record the final payload sequence once: a duplicate FIN from one + // side does not mean the other side has finished sending. + dir.fin_seq + .get_or_insert(pkt.tcp_seq.wrapping_add(pkt.wire_payload_len)); + } + let a_finished = self.a_to_b.fin_received(); + let b_finished = self.b_to_a.fin_received(); + self.state = match (a_finished, b_finished) { + (true, true) => TcpState::Closed, + (true, false) | (false, true) => TcpState::Closing, + (false, false) => self.state, + }; + let server_finished = match self.client_side { + ClientSide::AtoB => b_finished, + ClientSide::BtoA => a_finished, + ClientSide::Unknown => false, + }; + if server_finished { self.finish_pending_response(output); } @@ -430,14 +483,26 @@ impl TcpFlow { // Out-of-order (diff > 0): segment ahead of `expected`. Buffer it; // a future in-order arrival will drain it back into `buf`. let ooo = dir.ooo.get_or_insert_with(BTreeMap::new); - if ooo.len() >= OOO_CAP_SEGMENTS { - // Evict oldest (lowest seq). It is the segment furthest from - // the current `expected`, so most likely stranded; the freshly - // arrived segment is closer to the next in-order arrival. - if let Some(oldest) = ooo.keys().next().copied() { - ooo.remove(&oldest); + if let Some(buffered) = ooo.get_mut(&pkt.tcp_seq) { + // A duplicate needs no extra slot. Keep the longer segment so + // a shorter retransmission cannot erase an already-seen tail. + if pkt.payload.len() > buffered.len() { + *buffered = pkt.payload.clone(); + } else { + self.rexmit_ignored_pending = self.rexmit_ignored_pending.saturating_add(1); } + return; + } + if ooo.len() >= OOO_CAP_SEGMENTS { + let farthest = *ooo + .keys() + .max_by_key(|&&seq| seq.wrapping_sub(*expected)) + .expect("full OOO map"); self.ooo_drops_pending = self.ooo_drops_pending.saturating_add(1); + if pkt.tcp_seq.wrapping_sub(*expected) >= farthest.wrapping_sub(*expected) { + return; + } + ooo.remove(&farthest); } // `pkt.payload` is already a `Bytes` view; insert is a refcount bump. ooo.insert(pkt.tcp_seq, pkt.payload.clone()); @@ -446,6 +511,8 @@ impl TcpFlow { } fn try_parse_http(&mut self, output: &mut Vec) -> bool { + let a_capacity = self.a_to_b.buf.capacity(); + let b_capacity = self.b_to_a.buf.capacity(); // Determine which buffer is client and which is server. let ( client_buf, @@ -488,6 +555,8 @@ impl TcpFlow { server_last_ts, output, ); + self.a_to_b.reclaim_parsed_buffer(a_capacity); + self.b_to_a.reclaim_parsed_buffer(b_capacity); if result == ParseResult::NeedResync { tracing::trace!( @@ -508,6 +577,7 @@ impl TcpFlow { } fn finish_pending_response(&mut self, output: &mut Vec) { + let stamp_from = output.len(); let (server_buf, client_addr, server_addr, server_last_ts) = match self.client_side { ClientSide::AtoB => ( &mut self.b_to_a.buf, @@ -524,6 +594,7 @@ impl TcpFlow { ClientSide::Unknown => return, }; + let server_capacity = server_buf.capacity(); self.http_parser.finish_response( server_buf, &self.flow_key, @@ -532,6 +603,16 @@ impl TcpFlow { server_last_ts, output, ); + match self.client_side { + ClientSide::AtoB => self.b_to_a.reclaim_parsed_buffer(server_capacity), + ClientSide::BtoA => self.a_to_b.reclaim_parsed_buffer(server_capacity), + ClientSide::Unknown => {} + } + if let Some(process) = &self.process { + for event in &mut output[stamp_from..] { + event.set_process(Some(process.clone())); + } + } } pub fn is_closed(&self) -> bool { @@ -565,13 +646,17 @@ fn drain_ooo(dir: &mut DirState) { .as_mut() .expect("drain_ooo requires next_seq to be set"); - while let Some((&seq, _)) = ooo.iter().next() { - let seq_diff = seq.wrapping_sub(*expected) as i32; - if seq_diff > 0 { - // First entry still has a gap before it — stop. - break; - } - let bytes = ooo.remove(&seq).expect("just peeked"); + loop { + // Natural u32 order puts post-wrap segments before pre-wrap ones. + // Inspect the bounded map using offsets from the current stream head. + let next = ooo + .keys() + .copied() + .map(|seq| (seq, seq.wrapping_sub(*expected) as i32)) + .filter(|&(_, diff)| diff <= 0) + .min_by_key(|&(_, diff)| diff); + let Some((seq, seq_diff)) = next else { break }; + let bytes = ooo.remove(&seq).expect("just selected"); if seq_diff == 0 { dir.buf.extend_from_slice(&bytes); *expected = seq.wrapping_add(bytes.len() as u32); @@ -616,10 +701,9 @@ const CLEANUP_INTERVAL_US: i64 = 30_000_000; const FLOW_TIMEOUT_US: i64 = 120_000_000; /// Maximum out-of-order segments held per direction before eviction kicks in. -/// Worst-case memory ≈ 32 × MSS ≈ 48 KB / direction = 96 KB / flow. The cap is -/// also an implicit guarantee that the buffered window stays well under 2³¹ -/// bytes, so `BTreeMap`'s natural u32 ordering matches wraparound-aware logical -/// ordering used in `drain_ooo`. +/// Worst-case memory ≈ 32 × MSS ≈ 48 KB / direction = 96 KB / flow. +/// Sequence comparisons use wrapping offsets from the current stream head; +/// a count cap alone cannot make natural u32 ordering wraparound-safe. const OOO_CAP_SEGMENTS: usize = 32; /// A worker that processes packets for a set of flows (flow table). @@ -665,6 +749,26 @@ impl FlowWorker { out } + /// Drain in-flight responses at upstream EOF. This does not synthesize + /// an SSE terminal event: a truncated stream stays visibly incomplete. + pub fn finish(&mut self) -> Vec { + let mut out = Vec::new(); + for (_, mut flow) in self.flows.drain() { + flow.finish_pending_response(&mut out); + } + self.last_cleanup_by_source.clear(); + for event in &out { + match event { + HttpParseEvent::HttpResponse(_) => { + self.metrics.counter(Metric::HttpParseResp).inc() + } + HttpParseEvent::SseEvent(_) => self.metrics.counter(Metric::SseEventsParsed).inc(), + _ => {} + } + } + out + } + fn process_packet(&mut self, pkt: ParsedPacket, out: &mut Vec) { self.metrics.counter(Metric::NetPacketsParsed).inc(); @@ -836,6 +940,510 @@ mod tests { ) } + #[test] + fn test_completed_large_request_releases_idle_reassembly_allocation() { + // Two MiB is enough to exercise geometric buffer growth while keeping + // this metadata regression cheap. No captured body is logged or clipped. + let body_len = 2 * 1024 * 1024 + 17; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + let headers = format!( + "POST /large HTTP/1.1\r\nHost: localhost\r\nContent-Length: {body_len}\r\n\r\n" + ); + let mut seq = 100; + flow.push( + &make_pkt(&fk, Direction::AtoB, headers.as_bytes(), seq, 0), + &mut output, + ); + seq += headers.len() as u32; + let segment = [b'x'; 16 * 1024]; + let mut remaining = body_len; + while remaining > 0 { + let len = remaining.min(segment.len()); + flow.push( + &make_pkt(&fk, Direction::AtoB, &segment[..len], seq, 0), + &mut output, + ); + seq += len as u32; + remaining -= len; + } + let request = output + .iter() + .find_map(|event| match event { + HttpParseEvent::HttpRequest(request) => Some(request), + _ => None, + }) + .expect("complete request must be handed downstream"); + assert_eq!(request.body.len(), body_len); + assert!(request.body.iter().all(|&byte| byte == b'x')); + flow.push( + &make_pkt( + &fk, + Direction::BtoA, + b"HTTP/1.1 204 No Content\r\n\r\n", + 500, + 0, + ), + &mut output, + ); + assert!(output + .iter() + .any(|event| matches!(event, HttpParseEvent::HttpResponse(_)))); + output.clear(); // Downstream owners no longer account for any live body. + assert!(!flow.is_closed(), "keepalive connection stays available"); + assert!(flow.a_to_b.buf.is_empty()); + assert!(flow.b_to_a.buf.is_empty()); + // capacity() alone misses an empty split view at the end of a large + // shared allocation. try_reclaim never allocates: success proves that + // the idle direction still owns at least one whole former body buffer. + let visible_capacity = flow.a_to_b.buf.capacity(); + let retains_body_allocation = flow.a_to_b.buf.try_reclaim(body_len); + assert!(!retains_body_allocation, + "idle TCP direction retains a body-sized allocation: body_len={body_len}, visible_capacity={visible_capacity}, reclaimable_capacity={}", flow.a_to_b.buf.capacity()); + } + + #[test] + fn test_completed_large_response_releases_idle_reassembly_allocation() { + let body_len = 2 * 1024 * 1024 + 17; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + flow.push( + &make_pkt(&fk, Direction::AtoB, b"GET /large HTTP/1.1\r\n\r\n", 100, 0), + &mut output, + ); + let headers = format!("HTTP/1.1 200 OK\r\nContent-Length: {body_len}\r\n\r\n"); + let mut seq = 500; + flow.push( + &make_pkt(&fk, Direction::BtoA, headers.as_bytes(), seq, 0), + &mut output, + ); + seq += headers.len() as u32; + let segment = [b'y'; 16 * 1024]; + let mut remaining = body_len; + while remaining > 0 { + let len = remaining.min(segment.len()); + flow.push( + &make_pkt(&fk, Direction::BtoA, &segment[..len], seq, 0), + &mut output, + ); + seq += len as u32; + remaining -= len; + } + let response = output + .iter() + .find_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .expect("complete response must be handed downstream"); + assert_eq!(response.body.len(), body_len); + assert!(response.body.iter().all(|&byte| byte == b'y')); + output.clear(); + assert!(flow.b_to_a.buf.is_empty()); + assert!( + !flow.b_to_a.buf.try_reclaim(body_len), + "idle server direction retains a body-sized allocation" + ); + } + + #[test] + fn test_large_request_compacts_pipelined_tail_without_losing_bytes() { + let body_len = 2 * 1024 * 1024 + 17; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + let headers = format!("POST /large HTTP/1.1\r\nContent-Length: {body_len}\r\n\r\n"); + let mut seq = 100; + flow.push( + &make_pkt(&fk, Direction::AtoB, headers.as_bytes(), seq, 0), + &mut output, + ); + seq += headers.len() as u32; + let segment = [b'x'; 16 * 1024]; + let mut remaining = body_len; + while remaining > segment.len() { + flow.push( + &make_pkt(&fk, Direction::AtoB, &segment, seq, 0), + &mut output, + ); + seq += segment.len() as u32; + remaining -= segment.len(); + } + let next_request = b"POST /next HTTP/1.1\r\nContent-Length: 2\r\n\r\n{}"; + let mut last_segment = segment[..remaining].to_vec(); + last_segment.extend_from_slice(next_request); + flow.push( + &make_pkt(&fk, Direction::AtoB, &last_segment, seq, 0), + &mut output, + ); + assert_eq!( + &flow.a_to_b.buf[..], + next_request, + "unparsed pipelined tail is preserved verbatim" + ); + let request = output + .iter() + .find_map(|event| match event { + HttpParseEvent::HttpRequest(request) => Some(request), + _ => None, + }) + .expect("first request parsed"); + assert_eq!(request.body.len(), body_len); + assert!(request.body.iter().all(|&byte| byte == b'x')); + assert!( + !flow.a_to_b.buf.try_reclaim(body_len), + "small pipelined tail pins the former large request allocation" + ); + let response = b"HTTP/1.1 204 No Content\r\n\r\n"; + flow.push( + &make_pkt(&fk, Direction::BtoA, response, 500, 0), + &mut output, + ); + let next = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpRequest(request) => Some(request), + _ => None, + }) + .nth(1) + .expect("pipelined request parses after first response"); + assert_eq!(next.uri, "/next"); + assert_eq!(&next.body[..], b"{}"); + } + + #[test] + fn test_large_backing_is_released_after_pipelined_tail_drains_next_call() { + let first_body_len = 3 * 1024 * 1024 + 512 * 1024; + let next_body_len = 128 * 1024 - 128; + let large_capacity = 4 * 1024 * 1024; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + let first_headers = + format!("POST /large HTTP/1.1\r\nContent-Length: {first_body_len}\r\n\r\n"); + let mut seq = 100; + flow.push( + &make_pkt(&fk, Direction::AtoB, first_headers.as_bytes(), seq, 0), + &mut output, + ); + seq += first_headers.len() as u32; + // Fix the allocation size, not the packet size. Every data packet is + // <=16 KiB, including the eight OOO packets coalesced by drain_ooo. + flow.a_to_b.buf = BytesMut::with_capacity(large_capacity); + let segment = [b'x'; 16 * 1024]; + let mut remaining = first_body_len; + while remaining > segment.len() { + flow.push( + &make_pkt(&fk, Direction::AtoB, &segment, seq, 0), + &mut output, + ); + seq += segment.len() as u32; + remaining -= segment.len(); + } + let next_headers = + format!("POST /next HTTP/1.1\r\nContent-Length: {next_body_len}\r\n\r\n"); + let mut next_request = next_headers.as_bytes().to_vec(); + next_request.resize(next_request.len() + next_body_len, b'y'); + let mut ahead_seq = seq + remaining as u32; + for bytes in next_request.chunks(segment.len()) { + flow.push( + &make_pkt(&fk, Direction::AtoB, bytes, ahead_seq, 0), + &mut output, + ); + ahead_seq += bytes.len() as u32; + } + assert!( + output.is_empty(), + "first request waits for its missing last segment" + ); + flow.push( + &make_pkt(&fk, Direction::AtoB, &segment[..remaining], seq, 0), + &mut output, + ); + assert_eq!(&flow.a_to_b.buf[..], &next_request[..]); + assert!(flow.a_to_b.buf.len() > 64 * 1024); + assert!( + flow.a_to_b.buf.capacity() < 1024 * 1024, + "first parse hides the large backing behind a small remaining view" + ); + flow.push( + &make_pkt( + &fk, + Direction::BtoA, + b"HTTP/1.1 204 No Content\r\n\r\n", + 500, + 0, + ), + &mut output, + ); + let requests: Vec<_> = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpRequest(request) => Some(request), + _ => None, + }) + .collect(); + assert_eq!(requests.len(), 2); + assert_eq!(requests[0].body.len(), first_body_len); + assert!(requests[0].body.iter().all(|&byte| byte == b'x')); + assert_eq!(requests[1].uri, "/next"); + assert_eq!(requests[1].body.len(), next_body_len); + assert!(requests[1].body.iter().all(|&byte| byte == b'y')); + drop(requests); + output.clear(); + assert!(flow.a_to_b.buf.is_empty()); + assert!(!flow.a_to_b.buf.try_reclaim(large_capacity), "later parse must release the old large backing even after visible capacity falls below the threshold"); + } + + #[test] + fn test_small_sse_packets_reuse_existing_reassembly_allocation() { + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + flow.push( + &make_pkt( + &fk, + Direction::AtoB, + b"GET /stream HTTP/1.1\r\n\r\n", + 100, + 0, + ), + &mut output, + ); + let small_capacity = 16 * 1024; + flow.b_to_a.buf = BytesMut::with_capacity(small_capacity); + let headers = b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n"; + let mut seq = 500; + flow.push( + &make_pkt(&fk, Direction::BtoA, headers, seq, 0), + &mut output, + ); + seq += headers.len() as u32; + let chunk = b"b\r\ndata: one\n\n\r\n"; + for _ in 0..16 { + flow.push(&make_pkt(&fk, Direction::BtoA, chunk, seq, 0), &mut output); + seq += chunk.len() as u32; + assert!( + flow.b_to_a.buf.try_reclaim(small_capacity), + "small SSE packets should reuse capacity instead of freeing it every packet" + ); + } + assert_eq!( + output + .iter() + .filter(|event| matches!(event, HttpParseEvent::SseEvent(_))) + .count(), + 16 + ); + } + + #[test] + fn test_discard_buffers_releases_large_allocation() { + let mut direction = DirState::new(); + let large_capacity = 2 * 1024 * 1024; + direction.buf.resize(large_capacity, b'x'); + direction.discard_buffers(); + assert!(direction.buf.is_empty()); + assert!( + !direction.buf.try_reclaim(large_capacity), + "resync discard must release the previous large allocation" + ); + } + + // @scenario PROTO-TCP-LIFECYCLE-001 unit + #[test] + fn test_client_half_close_keeps_server_response_open() { + use crate::net::TCP_FIN; + for client_direction in [Direction::AtoB, Direction::BtoA] { + let server_direction = match client_direction { + Direction::AtoB => Direction::BtoA, + Direction::BtoA => Direction::AtoB, + }; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + let req = b"GET /stream HTTP/1.1\r\nHost: localhost\r\n\r\n"; + flow.push(&make_pkt(&fk, client_direction, req, 100, 0), &mut output); + let head = b"HTTP/1.1 200 OK\r\n\r\nfirst"; + flow.push(&make_pkt(&fk, server_direction, head, 500, 0), &mut output); + let fin = make_pkt( + &fk, + client_direction, + &[], + 100 + req.len() as u32, + TCP_FIN | TCP_ACK, + ); + flow.push(&fin, &mut output); + assert!( + !output + .iter() + .any(|e| matches!(e, HttpParseEvent::HttpResponse(_))), + "client FIN must not finish server response" + ); + flow.push(&fin, &mut output); + assert!( + !flow.is_closed(), + "retransmitted client FIN cannot close both directions" + ); + flow.push( + &make_pkt( + &fk, + server_direction, + b" second", + 500 + head.len() as u32, + TCP_ACK, + ), + &mut output, + ); + flow.push( + &make_pkt( + &fk, + server_direction, + &[], + 507 + head.len() as u32, + TCP_FIN | TCP_ACK, + ), + &mut output, + ); + assert!(flow.is_closed()); + let responses: Vec<_> = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert_eq!(&responses[0].body[..], b"first second"); + } + } + + // @scenario PROTO-TCP-LIFECYCLE-001 unit + #[test] + fn test_server_fin_waits_for_missing_response_bytes() { + use crate::net::TCP_FIN; + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + flow.push( + &make_pkt(&fk, Direction::AtoB, b"GET / HTTP/1.1\r\n\r\n", 100, 0), + &mut output, + ); + let head = b"HTTP/1.1 200 OK\r\n\r\nfirst"; + flow.push(&make_pkt(&fk, Direction::BtoA, head, 500, 0), &mut output); + let next = 500 + head.len() as u32; + flow.push( + &make_pkt(&fk, Direction::BtoA, b"second", next + 1, TCP_FIN | TCP_ACK), + &mut output, + ); + assert!( + !output + .iter() + .any(|e| matches!(e, HttpParseEvent::HttpResponse(_))), + "server FIN ahead of a gap cannot finish the response" + ); + flow.push( + &make_pkt(&fk, Direction::BtoA, b" ", next, TCP_ACK), + &mut output, + ); + let responses: Vec<_> = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert_eq!(&responses[0].body[..], b"first second"); + } + + #[test] + fn test_request_retransmission_does_not_reset_inflight_response() { + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + let mut output = Vec::new(); + let req = b"GET /data HTTP/1.1\r\nHost: localhost\r\n\r\n"; + flow.push(&make_pkt(&fk, Direction::AtoB, req, 100, 0), &mut output); + let head = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhe"; + flow.push(&make_pkt(&fk, Direction::BtoA, head, 500, 0), &mut output); + assert!( + !flow.push(&make_pkt(&fk, Direction::AtoB, req, 100, 0), &mut output), + "retransmission must not resync" + ); + flow.push( + &make_pkt(&fk, Direction::BtoA, b"llo", 500 + head.len() as u32, 0), + &mut output, + ); + assert_eq!( + output + .iter() + .filter(|e| matches!(e, HttpParseEvent::HttpRequest(_))) + .count(), + 1 + ); + let responses: Vec<_> = output + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert_eq!(&responses[0].body[..], b"hello"); + assert_eq!(flow.take_append_stats().2, 1); + } + + #[test] + fn test_ooo_capacity_preserves_gap_nearest_segments() { + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + flow.a_to_b.next_seq = Some(1); + for seq in 2..=34 { + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"x", seq, 0)); + } + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"a", 1, 0)); + assert_eq!(&flow.a_to_b.buf[..], b"axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + assert_eq!(flow.a_to_b.next_seq, Some(34)); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"z", 34, 0)); + assert_eq!(&flow.a_to_b.buf[..], b"axxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxz"); + assert_eq!(flow.take_append_stats().0, 1); + } + + #[test] + fn test_ooo_duplicate_at_capacity_does_not_evict_or_shorten() { + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + flow.a_to_b.next_seq = Some(1); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"bc", 2, 0)); + for seq in 4..=34 { + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"x", seq, 0)); + } + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"b", 2, 0)); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"a", 1, 0)); + assert_eq!(&flow.a_to_b.buf[..], b"abcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + assert_eq!(flow.a_to_b.next_seq, Some(35)); + assert_eq!( + flow.take_append_stats().0, + 0, + "same-sequence duplicate consumes no extra capacity" + ); + } + + #[test] + fn test_ooo_drain_across_sequence_wrap() { + let fk = test_flow_key(); + let mut flow = TcpFlow::new(fk.clone()); + flow.a_to_b.next_seq = Some(u32::MAX - 1); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"b", u32::MAX, 0)); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"d", 1, 0)); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"a", u32::MAX - 1, 0)); + flow.append_payload(&make_pkt(&fk, Direction::AtoB, b"c", 0, 0)); + assert_eq!(&flow.a_to_b.buf[..], b"abcd"); + assert_eq!(flow.a_to_b.next_seq, Some(2)); + } + #[test] fn test_mid_stream_join_discards_server_data_then_syncs() { let fk = test_flow_key(); @@ -1186,6 +1794,192 @@ mod tests { (FlowWorker::new(metrics.clone()), metrics) } + #[test] + fn test_worker_fin_before_first_server_payload_keeps_response() { + let (mut worker, metrics) = new_test_worker(); + let fk = test_flow_key(); + let mut events = Vec::new(); + for (direction, payload, seq, flags) in [ + (Direction::AtoB, &b"GET / HTTP/1.1\r\n\r\n"[..], 100, 0x10), + (Direction::AtoB, &b""[..], 118, 0x11), + (Direction::BtoA, &b""[..], 540, 0x11), + ] { + events.extend(worker.process(WorkerInput::Packet(make_pkt( + &fk, direction, payload, seq, flags, + )))); + } + assert_eq!( + worker.flow_count(), + 1, + "FIN without a sequence baseline must wait for response data" + ); + events.extend(worker.process(WorkerInput::Packet(make_pkt( + &fk, + Direction::BtoA, + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK", + 500, + 0x10, + )))); + let responses: Vec<_> = events + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert_eq!(&responses[0].body[..], b"OK"); + assert_eq!( + worker.flow_count(), + 0, + "both FINs are satisfied once the response arrives" + ); + assert_eq!(metrics.counter(Metric::HttpParseResp).get(), 1); + assert!( + worker.finish().is_empty(), + "EOF must not duplicate the response" + ); + } + + #[test] + fn test_worker_double_fin_with_baselines_reclaims_flow() { + let (mut worker, _) = new_test_worker(); + let fk = test_flow_key(); + let mut events = Vec::new(); + for (direction, payload, seq, flags) in [ + (Direction::AtoB, &b"GET / HTTP/1.1\r\n\r\n"[..], 100, 0x10), + ( + Direction::BtoA, + &b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"[..], + 500, + 0x10, + ), + (Direction::AtoB, &b""[..], 118, 0x11), + (Direction::BtoA, &b""[..], 540, 0x11), + ] { + events.extend(worker.process(WorkerInput::Packet(make_pkt( + &fk, direction, payload, seq, flags, + )))); + } + assert_eq!(worker.flow_count(), 0); + assert_eq!( + events + .iter() + .filter(|event| matches!(event, HttpParseEvent::HttpResponse(_))) + .count(), + 1 + ); + assert!(worker.finish().is_empty()); + } + + #[test] + fn test_worker_fin_without_server_baseline_still_expires() { + let (mut worker, metrics) = new_test_worker(); + let fk = test_flow_key(); + for (direction, payload, seq, flags) in [ + (Direction::AtoB, &b"GET / HTTP/1.1\r\n\r\n"[..], 100, 0x10), + (Direction::AtoB, &b""[..], 118, 0x11), + (Direction::BtoA, &b""[..], 540, 0x11), + ] { + let _ = worker.process(WorkerInput::Packet(make_pkt( + &fk, direction, payload, seq, flags, + ))); + } + assert_eq!(worker.flow_count(), 1); + let events = worker.process(WorkerInput::Heartbeat { + ts: 200_000_000, + source_id: String::new(), + }); + assert_eq!(worker.flow_count(), 0); + assert_eq!(metrics.counter(Metric::FlowsExpired).get(), 1); + assert!( + events + .iter() + .all(|event| matches!(event, HttpParseEvent::Heartbeat { .. })), + "missing headers must not invent a response" + ); + } + + #[test] + fn test_worker_finish_flushes_responses_once_with_metrics_and_process() { + let (mut worker, metrics) = new_test_worker(); + let process = ProcessInfo::new(42, "test-client"); + for (port, response) in [ + (5000, &b"HTTP/1.1 200 OK\r\n\r\npartial body"[..]), + ( + 5001, + &b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\r\ndata: final"[..], + ), + ] { + let fk = FlowKey::new( + String::new(), + "127.0.0.1".parse().unwrap(), + port, + "127.0.0.1".parse().unwrap(), + 8080, + ); + let mut request = + make_pkt_ts(&fk, Direction::AtoB, b"GET / HTTP/1.1\r\n\r\n", 100, 0, 10); + request.process = Some(process.clone()); + let _ = worker.process(WorkerInput::Packet(request)); + let events = worker.process(WorkerInput::Packet(make_pkt_ts( + &fk, + Direction::BtoA, + response, + 500, + 0, + 20, + ))); + assert!(events.is_empty()); + } + let events = worker.finish(); + let mut responses: Vec<_> = events + .iter() + .filter_map(|event| match event { + HttpParseEvent::HttpResponse(response) => Some(response), + _ => None, + }) + .collect(); + responses.sort_by_key(|response| response.client_addr.1); + assert_eq!(responses.len(), 2); + assert_eq!(&responses[0].body[..], b"partial body"); + assert_eq!(responses[0].complete_timestamp_us, 20); + assert!(responses[1].body.is_empty()); + let sse: Vec<_> = events + .iter() + .filter_map(|event| match event { + HttpParseEvent::SseEvent(event) => Some(event), + _ => None, + }) + .collect(); + assert_eq!(sse.len(), 1); + assert_eq!(sse[0].data, "final"); + assert_eq!(sse[0].process.as_ref(), Some(&process)); + assert!(responses + .iter() + .all(|response| response.process.as_ref() == Some(&process))); + assert_eq!(metrics.counter(Metric::HttpParseResp).get(), 2); + assert_eq!(metrics.counter(Metric::SseEventsParsed).get(), 1); + assert_eq!(worker.flow_count(), 0); + assert!(worker.finish().is_empty(), "EOF drain is idempotent"); + } + + #[test] + fn test_worker_finish_does_not_invent_response_without_headers() { + let (mut worker, metrics) = new_test_worker(); + let fk = test_flow_key(); + let _ = worker.process(WorkerInput::Packet(make_pkt( + &fk, + Direction::AtoB, + b"GET / HTTP/1.1\r\n\r\n", + 100, + 0, + ))); + assert!(worker.finish().is_empty()); + assert_eq!(metrics.counter(Metric::HttpParseResp).get(), 0); + assert_eq!(worker.flow_count(), 0); + } + #[test] fn test_flow_timeout_cleanup() { let (mut worker, metrics) = new_test_worker(); @@ -1551,11 +2345,9 @@ mod tests { } #[test] - fn test_ooo_cap_eviction_evicts_oldest_and_bumps_drop() { - // Buffer 33 OOO segments at seqs 100, 200, ..., 3300 — gap to - // expected=1 is huge, so all stay buffered. The 33rd insert must - // hit the cap (32) and evict the lowest-seq entry (seq=100), bumping - // TcpOutOfOrderDrops once. The smallest remaining seq is 200. + fn test_ooo_cap_retains_nearest_segments_and_bumps_drop() { + // Keep the 32 segments nearest expected=1. A farther 33rd arrival + // must not discard seq=100, which would leave the first gap unfillable. let (mut worker, metrics) = new_test_worker(); let fk = test_flow_key(); handshake(&mut worker, &fk); @@ -1574,10 +2366,10 @@ mod tests { assert_eq!( metrics.counter(Metric::TcpOutOfOrderBuffered).get(), - (OOO_CAP_SEGMENTS as u64) + 1 + OOO_CAP_SEGMENTS as u64 ); assert_eq!(metrics.counter(Metric::TcpOutOfOrderDrops).get(), 1); - assert_eq!(flow_a_to_b_ooo_smallest_seq(&worker, &fk), Some(200)); + assert_eq!(flow_a_to_b_ooo_smallest_seq(&worker, &fk), Some(100)); } #[test] diff --git a/server/h-storage-clickhouse/Cargo.toml b/server/h-storage-clickhouse/Cargo.toml index 62338b22..0f94ca38 100644 --- a/server/h-storage-clickhouse/Cargo.toml +++ b/server/h-storage-clickhouse/Cargo.toml @@ -17,7 +17,7 @@ tokio.workspace = true tracing.workspace = true serde.workspace = true serde_json.workspace = true +uuid.workspace = true [dev-dependencies] -uuid.workspace = true bytes.workspace = true diff --git a/server/h-storage-clickhouse/README.md b/server/h-storage-clickhouse/README.md index b0411f64..0bf4249c 100644 --- a/server/h-storage-clickhouse/README.md +++ b/server/h-storage-clickhouse/README.md @@ -16,15 +16,54 @@ Module layout mirrors `h-storage-duckdb` 1:1 (`schema`, `rows`, `calls`, | Table | Engine | ORDER BY | |---|---|---| -| `llm_calls`, `http_exchanges` | `MergeTree` | `(request_time, id)` | +| `spans`, `http_exchanges` | `MergeTree` | `(request_time, id)` | | `llm_metrics` | `MergeTree` | `(granularity, timestamp, wire_api, model, server_ip)` | | `llm_finish_metrics` | `MergeTree` | `(granularity, timestamp, finish_reason, …)` | -| `agent_turns` | `ReplacingMergeTree(_version)` | `turn_id` | - -`agent_turns` is the only mutated table (`update_turn_metadata`): reads use -`FINAL`, and updates re-insert the full row with a higher `_version`. Timestamps -are `DateTime64(6, 'UTC')`; the crate maps them to `i64` microseconds (matching -the domain models — no chrono/time dependency). +| `traces` | `ReplacingMergeTree(_version)` | `turn_id` | +| `trace_pair_candidates` | `ReplacingMergeTree(_version)` | `(start_time, turn_id)` | +| `trace_pair_index_state` | `ReplacingMergeTree(_revision)` | `job` | +| `trace_pair_repairs` | `ReplacingMergeTree(_revision)` | `operation_id` | + +`traces` stores authoritative turns: reads use `FINAL`, and metadata updates +re-insert complete rows with a higher `_version`. The additive +`spans.tokens_estimated` summary is `Nullable(Bool)`: new writes compute it with +the shared Rust helper; legacy `NULL` rows are backfilled in paced, bounded +batches. Span lists omit `response_body` from their main projection and load +bodies only for legacy unknowns when required. Detail and export reads keep +complete bodies. Timestamps are `DateTime64(6, 'UTC')`; the crate maps them to +`i64` microseconds (matching the domain models — no chrono/time dependency). + +Summary maintenance walks pages of 128 physical keys and hydrates only unknown +rows requiring body inspection. It uses a 1 MiB soft body target, one acknowledged +mutation at a time, and at least one second between steps. A restart can revisit +completed key pages; persisted summary values avoid fetching their bodies again. +Mutation I/O follows the size of the affected ClickHouse part columns. + +Topology streams compact trace projections and resolves first-span endpoints +in bounded batches with time predicates. Endpoint frequencies preserve proxy +pair counts across batches; exceeding the resource budget returns an explicit +error instead of truncating the graph. + +Pairing uses `trace_pair_candidates_mv` to copy every trace version, including +already-paired versions, into the time-ordered candidate table. A sweep pages the +latest unpaired candidates with deterministic timestamp/ID cursors and keeps +fingerprint clusters open across page boundaries. Initialization progress and +object identities make backfill resumable. A new job also covers pre-view rows +with future event timestamps, using a frozen source high-water mark captured +after installing the view. Ordinary forward windows reuse readiness; widening +the lower bound or rebuilding the index can require another authoritative scan. +Atomic objects retain their UUID identity. Ordinary objects use a persistent +per-creation generation in their table/view comments, so recreation also +invalidates readiness after a restart. Existing untagged Ordinary objects are +migrated once before reusing readiness, preserving unrelated comments. + +Before batched metadata writes, `trace_pair_repairs` stores the original member +IDs and patches. Pending work replays from fresh traces before discovery, even +when its members have left the current window. Missing rows stay deleted and +unrelated metadata survives. The backend serializes pairing and trace retention; +expired candidate versions are removed before authoritative traces. Application +budgets fail explicitly for oversized clusters or repair plans. Physical granule +reads, part mutations and individual large rows remain server/storage costs. ## Configuration diff --git a/server/h-storage-clickhouse/src/calls.rs b/server/h-storage-clickhouse/src/calls.rs index 8cb1affe..940fb3c3 100644 --- a/server/h-storage-clickhouse/src/calls.rs +++ b/server/h-storage-clickhouse/src/calls.rs @@ -1,5 +1,7 @@ //! `spans` table I/O — write + paginated / by-id / by-id-list reads. +use std::collections::HashMap; + use clickhouse::Row; use serde::Deserialize; @@ -34,6 +36,7 @@ struct CallListRow { id: String, source_id: String, request_time_ms: i64, + request_time_us: i64, wire_api: String, model: String, status_code: Option, @@ -47,7 +50,7 @@ struct CallListRow { server_ip: String, server_port: u16, request_path: String, - response_body: Option, + tokens_estimated: Option, is_agent_request: bool, tool_surface: Option, agent_topology: Option, @@ -209,22 +212,84 @@ impl ClickHouseBackend { let offset = (query.page.saturating_sub(1)) as u64 * query.page_size as u64; let items_sql = format!( - "SELECT id, source_id, toUnixTimestamp64Milli(request_time) AS request_time_ms, \ + "SELECT id, source_id, toUnixTimestamp64Milli(request_time) AS request_time_ms, request_time AS request_time_us, \ wire_api, model, status_code, is_stream, finish_reason, ttft_ms, e2e_latency_ms, \ input_tokens, output_tokens, client_ip, server_ip, server_port, request_path, \ - response_body, is_agent_request, tool_surface, agent_topology, tool_call_count, \ + tokens_estimated, is_agent_request, tool_surface, agent_topology, tool_call_count, \ tool_names_json, process_pid, process_comm, process_exe \ FROM spans WHERE {where_sql} \ ORDER BY {} {sort_order}, id ASC LIMIT {} OFFSET {offset}", query.sort_by, query.page_size, ); - let rows = self + let mut rows = self .client .query(&items_sql) .fetch_all::() .await .map_err(|e| ch_err("query_spans items", e))?; + // Only unknown positive-token page keys need compatibility bodies. Zero + // tokens are exact without inspecting JSON; summarized pages do no lookup. + for page in rows.chunks_mut(128) { + let keys: Vec<_> = page + .iter() + .filter(|r| { + r.tokens_estimated.is_none() + && (r.input_tokens.unwrap_or(0) > 0 || r.output_tokens.unwrap_or(0) > 0) + }) + .map(|r| crate::summary::SpanKey { + request_time: r.request_time_us, + id: r.id.clone(), + }) + .collect(); + if keys.is_empty() { + continue; + } + #[derive(Row, Deserialize)] + struct UnknownRow { + request_time: i64, + id: String, + tokens_estimated: Option, + input_tokens: Option, + output_tokens: Option, + response_body: Option, + } + let tuples = keys + .iter() + .map(|k| k.tuple_sql()) + .collect::>() + .join(","); + let first = keys.iter().map(|k| k.request_time).min().unwrap(); + let last = keys.iter().map(|k| k.request_time).max().unwrap(); + let sql=format!("SELECT request_time,id,tokens_estimated,input_tokens,output_tokens,if(isNull(tokens_estimated),response_body,CAST(NULL AS Nullable(String))) AS response_body FROM spans WHERE request_time >= fromUnixTimestamp64Micro({first}) AND request_time <= fromUnixTimestamp64Micro({last}) AND (request_time,id) IN ({tuples})"); + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("list legacy summaries", e))?; + let mut summaries = HashMap::new(); + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("list legacy summaries", e))? + { + let value = row.tokens_estimated.unwrap_or_else(|| { + derive_tokens_estimated( + row.input_tokens, + row.output_tokens, + row.response_body.as_deref(), + ) + }); + summaries.insert((row.request_time, row.id), value); + } + for row in page { + if row.tokens_estimated.is_none() { + row.tokens_estimated = summaries + .get(&(row.request_time_us, row.id.clone())) + .copied(); + } + } + } let items = rows.into_iter().map(call_list_item).collect(); Ok(SpansPage { total, items }) } @@ -402,8 +467,9 @@ fn row_process(pid: Option, comm: Option, exe: Option) -> O } fn call_list_item(r: CallListRow) -> SpanListItem { - let tokens_estimated = - derive_tokens_estimated(r.input_tokens, r.output_tokens, r.response_body.as_deref()); + let tokens_estimated = r + .tokens_estimated + .unwrap_or_else(|| derive_tokens_estimated(r.input_tokens, r.output_tokens, None)); let tool_names = parse_json_string_list(r.tool_names_json.as_deref()); let process = row_process(r.process_pid, r.process_comm, r.process_exe); SpanListItem { diff --git a/server/h-storage-clickhouse/src/lib.rs b/server/h-storage-clickhouse/src/lib.rs index 24ddf6f6..bbedba51 100644 --- a/server/h-storage-clickhouse/src/lib.rs +++ b/server/h-storage-clickhouse/src/lib.rs @@ -18,21 +18,29 @@ mod client; mod distincts; mod exchanges; #[cfg(test)] -#[cfg(test)] mod it; +mod metrics; +mod pairing; +mod pairing_groups; +mod pairing_repair; +#[cfg(test)] +mod pairing_tests; #[cfg(test)] mod query_tests; +mod retention; #[cfg(test)] mod retention_tests; -#[cfg(test)] -mod test_mock; -mod metrics; -mod retention; mod rows; mod schema; mod services; mod sessions; mod sql; +mod summary; +#[cfg(test)] +mod summary_tests; +#[cfg(test)] +mod test_mock; +mod topology; mod turns; use async_trait::async_trait; @@ -43,7 +51,7 @@ use h_common::error::Result; use h_llm::model::LlmCall; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_protocol::HttpExchange; -use h_turn::{Trace, PairCandidate}; +use h_turn::{PairCandidate, Trace}; use h_storage::query::*; use h_storage::retention::{RetentionPolicy, RetentionReport}; @@ -64,6 +72,11 @@ pub struct ClickHouseBackend { pub(crate) database: String, /// When true, `apply_retention` follows each DELETE with `OPTIMIZE FINAL`. pub(crate) optimize_on_sweep: bool, + pub(crate) summary_worker: summary::SummaryWorker, + pub(crate) pairing_gate: tokio::sync::Mutex<()>, + pub(crate) pairing_limits: pairing::Limits, + #[cfg(test)] + pub(crate) pairing_faults: pairing_tests::Faults, } impl ClickHouseBackend { @@ -84,6 +97,11 @@ impl ClickHouseBackend { password: config.password.clone(), database: config.database.clone(), optimize_on_sweep: config.optimize_on_sweep, + summary_worker: summary::SummaryWorker::default(), + pairing_gate: tokio::sync::Mutex::new(()), + pairing_limits: pairing::Limits::default(), + #[cfg(test)] + pairing_faults: pairing_tests::Faults::default(), }) } } @@ -91,7 +109,9 @@ impl ClickHouseBackend { #[async_trait] impl StorageBackend for ClickHouseBackend { async fn init(&self) -> Result<()> { - schema::init(self).await + schema::init(self).await?; + self.summary_worker.start(self.client.clone()); + Ok(()) } async fn write_spans(&self, calls: Vec) -> Result<()> { @@ -118,10 +138,7 @@ impl StorageBackend for ClickHouseBackend { ClickHouseBackend::query_http_exchange_by_id(self, id).await } - async fn query_http_exchanges( - &self, - query: &HttpExchangesQuery, - ) -> Result { + async fn query_http_exchanges(&self, query: &HttpExchangesQuery) -> Result { ClickHouseBackend::query_http_exchanges(self, query).await } @@ -222,10 +239,7 @@ impl StorageBackend for ClickHouseBackend { ClickHouseBackend::query_session_by_id(self, source_id, session_id).await } - async fn query_session_traces( - &self, - query: &SessionTracesQuery, - ) -> Result { + async fn query_session_traces(&self, query: &SessionTracesQuery) -> Result { ClickHouseBackend::query_session_traces(self, query).await } @@ -256,6 +270,16 @@ impl StorageBackend for ClickHouseBackend { ClickHouseBackend::apply_retention(self, policy).await } + async fn sweep_pair_window( + &self, + start_us: i64, + end_us: i64, + ) -> Result> { + ClickHouseBackend::sweep_pair_window(self, start_us, end_us) + .await + .map(Some) + } + async fn query_pair_candidates( &self, start_us: i64, diff --git a/server/h-storage-clickhouse/src/pairing.rs b/server/h-storage-clickhouse/src/pairing.rs new file mode 100644 index 00000000..c61874b2 --- /dev/null +++ b/server/h-storage-clickhouse/src/pairing.rs @@ -0,0 +1,476 @@ +//! Time-ordered pairing discovery and recoverable candidate-index initialization. +//! Authoritative traces remain complete; this index contains only classifier data. +use clickhouse::Row; +use h_common::error::{AppError, Result}; +use h_storage::{convert::parse_json_string_list, pair_sweeper::SweepStats}; +use h_turn::PairCandidate; +use serde::{Deserialize, Serialize}; + +use crate::client::{ch_err, insert_all}; +use crate::pairing_groups::{calls_bytes, candidate_bytes, Clusters}; +use crate::sql::escape_str; +use crate::turns::next_trace_version; +use crate::ClickHouseBackend; + +#[derive(Clone, Copy)] +pub(crate) struct Limits { + pub(crate) page_rows: usize, + pub(crate) write_rows: usize, + pub(crate) retained_bytes: usize, + pub(crate) open_members: usize, + pub(crate) plan_bytes: usize, + pub(crate) write_bytes: usize, +} +impl Default for Limits { + fn default() -> Self { + Self { + page_rows: 256, + write_rows: 128, + retained_bytes: 64 * 1024 * 1024, + open_members: 100_000, + plan_bytes: 8 * 1024 * 1024, + write_bytes: 8 * 1024 * 1024, + } + } +} +pub(crate) fn budget(reason: &str) -> AppError { + AppError::Storage(format!( + "ClickHouse pairing aggregation budget exceeded ({reason})" + )) +} + +pub(crate) const CREATE_CANDIDATES: &str = "CREATE TABLE IF NOT EXISTS trace_pair_candidates ( + turn_id String, session_id String, agent_kind String, wire_api String, + start_time DateTime64(6, 'UTC'), end_time DateTime64(6, 'UTC'), + call_count UInt32, total_input_tokens UInt64, total_output_tokens UInt64, + final_finish_reason Nullable(String), models_used Nullable(String), + client_ip String, server_ip String, proxy_role String, _version UInt64 +) ENGINE=ReplacingMergeTree(_version) ORDER BY (start_time,turn_id)"; +const CREATE_STATE: &str = "CREATE TABLE IF NOT EXISTS trace_pair_index_state ( + job String, destination_id String, view_id String, lo Int64, hi Int64, + cursor Nullable(String), ready UInt8, _revision UInt64 +) ENGINE=ReplacingMergeTree(_revision) ORDER BY job"; +const CREATE_REPAIRS: &str = "CREATE TABLE IF NOT EXISTS trace_pair_repairs ( + operation_id String, created_at Int64, plan String, _revision UInt64 +) ENGINE=ReplacingMergeTree(_revision) ORDER BY operation_id"; +const CREATE_VIEW: &str = "CREATE MATERIALIZED VIEW IF NOT EXISTS trace_pair_candidates_mv +TO trace_pair_candidates AS SELECT turn_id,session_id,agent_kind,wire_api,start_time,end_time, +call_count,total_input_tokens,total_output_tokens,final_finish_reason,models_used,client_ip,server_ip, +JSONExtractString(coalesce(metadata,''),'proxy','role') AS proxy_role,_version FROM traces AS pair_source"; + +const ZERO_UUID: &str = "00000000-0000-0000-0000-000000000000"; +const GENERATION_PREFIX: &str = "heron-pair-generation:"; + +const PROJECTION: &str = "turn_id,session_id,agent_kind,wire_api, + start_time,end_time, + call_count,total_input_tokens,total_output_tokens,final_finish_reason,models_used,client_ip,server_ip"; + +#[derive(Clone, Row, Serialize, Deserialize)] +pub(crate) struct CandidateRow { + pub(crate) turn_id: String, + session_id: String, + agent_kind: String, + wire_api: String, + pub(crate) start_time: i64, + end_time: i64, + call_count: u32, + total_input_tokens: u64, + total_output_tokens: u64, + final_finish_reason: Option, + models_used: Option, + client_ip: String, + server_ip: String, + proxy_role: String, + _version: u64, +} +impl CandidateRow { + fn retained_bytes(&self) -> usize { + let strings = [ + &self.turn_id, + &self.session_id, + &self.agent_kind, + &self.wire_api, + &self.client_ip, + &self.server_ip, + &self.proxy_role, + ]; + 2 * std::mem::size_of::() + + strings.into_iter().map(|s| s.capacity()).sum::() + + self + .final_finish_reason + .as_ref() + .map_or(0, String::capacity) + + self.models_used.as_ref().map_or(0, String::capacity) + } + fn into_candidate(self) -> PairCandidate { + let primary_model = parse_json_string_list(self.models_used.as_deref()) + .into_iter() + .next(); + PairCandidate { + turn_id: self.turn_id, + session_id: self.session_id, + agent_kind: self.agent_kind, + wire_api: self.wire_api, + start_time_us: self.start_time, + end_time_us: self.end_time, + call_count: self.call_count, + total_input_tokens: self.total_input_tokens, + total_output_tokens: self.total_output_tokens, + final_finish_reason: self.final_finish_reason, + primary_model, + network_view: format!("{}->{}", self.client_ip, self.server_ip), + } + } +} +#[derive(Row, Serialize, Deserialize)] +struct IndexState { + job: String, + destination_id: String, + view_id: String, + lo: i64, + hi: i64, + cursor: Option, + ready: u8, + _revision: u64, +} +#[derive(Row, Deserialize)] +struct Identity { + name: String, + identity: String, + comment: String, +} + +pub(crate) async fn create_schema(backend: &ClickHouseBackend) -> Result<()> { + // The view must exist before any authoritative backfill starts. Comments + // persist a creation identity even on Ordinary, where UUIDs are all zero. + // IF NOT EXISTS leaves an existing object's generation/comments intact. + for ddl in [CREATE_CANDIDATES, CREATE_STATE, CREATE_REPAIRS, CREATE_VIEW] { + let sql = if ddl == CREATE_CANDIDATES || ddl == CREATE_VIEW { + format!( + "{ddl} COMMENT '{GENERATION_PREFIX}{}'", + uuid::Uuid::now_v7() + ) + } else { + ddl.to_owned() + }; + backend.exec(&sql).await?; + } + Ok(()) +} + +impl ClickHouseBackend { + async fn pair_identities(&self) -> Result> { + self.client.query("SELECT name,toString(uuid) AS identity,comment FROM system.tables WHERE database=currentDatabase() AND name IN ('trace_pair_candidates','trace_pair_candidates_mv','trace_pair_index_state','trace_pair_repairs') ORDER BY name") + .fetch_all::().await.map_err(|e|ch_err("pairing index identities",e)) + } + + async fn pair_object_identity(&self, object: &Identity) -> Result { + if object.identity != ZERO_UUID { + return Ok(object.identity.clone()); + } + if let Some(generation) = object + .comment + .lines() + .find_map(|line| uuid::Uuid::parse_str(line.strip_prefix(GENERATION_PREFIX)?).ok()) + { + return Ok(format!("{GENERATION_PREFIX}{generation}")); + } + // Migrate untagged Ordinary objects once, before trusting any old + // zero-ID ready marker. Preserve operator comments byte-for-byte. + let generation = format!("{GENERATION_PREFIX}{}", uuid::Uuid::now_v7()); + let comment = if object.comment.is_empty() { + generation.clone() + } else { + format!("{}\n{generation}", object.comment) + }; + self.exec(&format!( + "ALTER TABLE {} MODIFY COMMENT '{}'", + object.name, + escape_str(&comment) + )) + .await?; + Ok(generation) + } + + pub(crate) async fn ensure_pair_index(&self, lo: i64, hi: i64) -> Result<()> { + let mut identities = self.pair_identities().await?; + if identities.len() != 4 { + create_schema(self).await?; + identities = self.pair_identities().await?; + } + let identity = |name: &str| { + identities.iter().find(|i| i.name == name).ok_or_else(|| { + AppError::Storage(format!("missing ClickHouse pairing object {name}")) + }) + }; + let destination = self + .pair_object_identity(identity("trace_pair_candidates")?) + .await?; + let view = self + .pair_object_identity(identity("trace_pair_candidates_mv")?) + .await?; + let existing=self.client.query("SELECT job,destination_id,view_id,lo,hi,cursor,ready,_revision FROM trace_pair_index_state FINAL WHERE job='initialize' LIMIT 1") + .fetch_optional::().await.map_err(|e|ch_err("pairing initialization state",e))?; + let mut state = match existing { + Some(state) if state.destination_id == destination && state.view_id == view => state, + old => IndexState { + job: "initialize".into(), + destination_id: destination, + view_id: view, + lo, + hi: self.pair_backfill_upper_bound(hi).await?, + cursor: None, + ready: 0, + _revision: next_trace_version( + old.map_or(0, |s| s._revision), + crate::turns::now_micros(), + )?, + }, + }; + // The fixed backfill extends through the source highwater captured + // after MV installation, including pre-view future timestamps. Later + // upper windows are covered; widening lo still needs older history. + if state.ready != 0 && lo >= state.lo { + return Ok(()); + } + if state.ready != 0 { + state.lo = lo; + state.hi = self.pair_backfill_upper_bound(hi).await?; + state.cursor = None; + state.ready = 0; + } + self.save_pair_state(&mut state).await?; + loop { + let cursor = state + .cursor + .as_ref() + .map(|id| format!(" AND turn_id>'{}'", escape_str(id))) + .unwrap_or_default(); + let sql=format!("SELECT {PROJECTION},JSONExtractString(coalesce(metadata,''),'proxy','role') AS proxy_role,_version FROM traces FINAL WHERE start_time>=fromUnixTimestamp64Micro({}) AND start_time() + .map_err(|e| ch_err("pairing backfill page", e))?; + let mut rows = Vec::new(); + let mut bytes = 0usize; + let mut last = None; + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("pairing backfill row", e))? + { + last = Some(row.turn_id.clone()); + bytes = bytes.saturating_add(row.retained_bytes()); + rows.push(row); + if bytes + >= self + .pairing_limits + .write_bytes + .min(self.pairing_limits.retained_bytes) + { + // At most one indivisible projection row overshoots the + // byte target. Never collect all large rows in a page. + insert_all!( + self.client, + "trace_pair_candidates", + CandidateRow, + std::mem::take(&mut rows) + ); + bytes = 0; + } + } + if !rows.is_empty() { + insert_all!(self.client, "trace_pair_candidates", CandidateRow, rows); + } + let Some(last) = last else { + break; + }; + #[cfg(test)] + if self + .pairing_faults + .after_backfill_page + .swap(false, std::sync::atomic::Ordering::SeqCst) + { + return Err(AppError::Storage( + "synthetic failure after committed backfill page".into(), + )); + } + state.cursor = Some(last); + self.save_pair_state(&mut state).await?; + } + state.ready = 1; + self.save_pair_state(&mut state).await?; + // An interrupted job resumes its original bounds. If this caller asks + // for still older history, complete a separate fixed-window job now. + if lo < state.lo { + state.lo = lo; + state.hi = self.pair_backfill_upper_bound(hi).await?; + state.cursor = None; + state.ready = 0; + self.save_pair_state(&mut state).await?; + // Box only this exceptional recovery recursion; normal sweeps do + // not recreate state or walk authoritative history. + Box::pin(self.ensure_pair_index(lo, hi)).await?; + } + Ok(()) + } + + async fn pair_backfill_upper_bound(&self, requested_hi: i64) -> Result { + #[derive(Row, Deserialize)] + struct SourceHighwater { + max_start: Option, + } + // Start time is immutable across versions. The MV is already installed, + // so only this finite source snapshot needs authoritative backfilling. + // Capture once per new/rebuilt/widened job, never on ready reuse/pages. + let source = self.client.query("SELECT maxOrNull(toUnixTimestamp64Micro(start_time)) AS max_start FROM traces SETTINGS max_threads=1,max_memory_usage=268435456") + .fetch_one::().await.map_err(|e|ch_err("pairing source highwater",e))?; + match source.max_start { + None => Ok(requested_hi), + Some(max_start) => max_start + .checked_add(1) + .map(|exclusive| requested_hi.max(exclusive)) + .ok_or_else(|| { + AppError::Storage("ClickHouse pairing source timestamp exhausted".into()) + }), + } + } + + async fn save_pair_state(&self, state: &mut IndexState) -> Result<()> { + state._revision = next_trace_version(state._revision, crate::turns::now_micros())?; + let mut insert = self + .client + .insert::("trace_pair_index_state") + .await + .map_err(|e| ch_err("pairing state insert", e))?; + insert + .write(state) + .await + .map_err(|e| ch_err("pairing state write", e))?; + insert + .end() + .await + .map_err(|e| ch_err("pairing state commit", e)) + } + + pub(crate) async fn pair_page( + &self, + lo: i64, + hi: i64, + cursor: Option<&(i64, String)>, + available_bytes: usize, + ) -> Result> { + let after=cursor.map(|(time,id)|format!(" AND start_time>=fromUnixTimestamp64Micro({time}) AND (start_time,turn_id)>(fromUnixTimestamp64Micro({time}),'{}')",escape_str(id))).unwrap_or_default(); + let sql=format!("SELECT {PROJECTION},proxy_role,_version FROM trace_pair_candidates FINAL WHERE start_time>=fromUnixTimestamp64Micro({lo}) AND start_time() + .map_err(|e| ch_err("pairing candidate page", e))?; + let mut result = Vec::new(); + let mut bytes = 0usize; + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("pairing candidate row", e))? + { + let candidate = row.into_candidate(); + bytes = bytes.saturating_add(candidate_bytes(&candidate)); + if bytes > available_bytes { + return Err(budget("candidate page")); + } + result.push(candidate); + } + Ok(result) + } + + pub(crate) async fn indexed_pair_candidates( + &self, + lo: i64, + hi: i64, + ) -> Result> { + let _gate = self.pairing_gate.lock().await; + self.ensure_pair_index(lo, hi).await?; + let mut cursor = None; + let mut result = Vec::new(); + let mut bytes = 0usize; + loop { + let page = self + .pair_page( + lo, + hi, + cursor.as_ref(), + self.pairing_limits.retained_bytes.saturating_sub(bytes), + ) + .await?; + if page.is_empty() { + break; + } + for c in page { + bytes = bytes.saturating_add(crate::pairing_groups::candidate_bytes(&c)); + if result.len() >= self.pairing_limits.open_members + || bytes > self.pairing_limits.retained_bytes + { + return Err(budget("candidate collection")); + } + cursor = Some((c.start_time_us, c.turn_id.clone())); + result.push(c); + } + } + Ok(result) + } + + pub(crate) async fn sweep_pair_window(&self, lo: i64, hi: i64) -> Result { + let _gate = self.pairing_gate.lock().await; + self.ensure_pair_index(lo, hi).await?; + let mut stats = SweepStats { + candidates_scanned: 0, + pairs_assigned: 0, + turns_tagged: 0, + }; + self.replay_pair_repairs(&mut stats).await?; + let mut clusters = Clusters::new(self.pairing_limits); + let mut cursor = None; + loop { + let page = self + .pair_page( + lo, + hi, + cursor.as_ref(), + self.pairing_limits + .retained_bytes + .saturating_sub(clusters.retained_bytes()), + ) + .await?; + if page.is_empty() { + break; + } + let mut page_bytes = calls_bytes(&page); + for candidate in page { + page_bytes -= candidate_bytes(&candidate); + cursor = Some((candidate.start_time_us, candidate.turn_id.clone())); + stats.candidates_scanned += 1; + let closed = clusters.push(candidate)?; + let mut closed_bytes: usize = closed.iter().map(|calls| calls_bytes(calls)).sum(); + for cluster in closed { + closed_bytes -= calls_bytes(&cluster); + let other_bytes = clusters + .retained_bytes() + .saturating_add(page_bytes) + .saturating_add(closed_bytes); + self.classify_pair_cluster(cluster, other_bytes, &mut stats) + .await?; + } + } + } + let closed = clusters.finish(); + let mut remaining: usize = closed.iter().map(|calls| calls_bytes(calls)).sum(); + for cluster in closed { + remaining -= calls_bytes(&cluster); + self.classify_pair_cluster(cluster, remaining, &mut stats) + .await?; + } + Ok(stats) + } +} diff --git a/server/h-storage-clickhouse/src/pairing_groups.rs b/server/h-storage-clickhouse/src/pairing_groups.rs new file mode 100644 index 00000000..92e998ee --- /dev/null +++ b/server/h-storage-clickhouse/src/pairing_groups.rs @@ -0,0 +1,198 @@ +//! Bounded open clusters. Page edges never end a fingerprint cluster. +use crate::pairing::{budget, Limits}; +use h_common::error::Result; +use h_turn::{proxy_pair::MAX_REQ_TIME_GAP_US, PairCandidate}; +use std::collections::{BTreeMap, BTreeSet}; + +type Fingerprint = (String, String, u32, u64, u64); +fn fingerprint(c: &PairCandidate) -> Fingerprint { + ( + c.session_id.clone(), + c.agent_kind.clone(), + c.call_count, + c.total_input_tokens, + c.total_output_tokens, + ) +} +pub(crate) fn candidate_bytes(c: &PairCandidate) -> usize { + // Two row slots cover spare Vec capacity. Extra key/deadline/tree overhead + // is deliberately conservative, including owned fingerprint copies. + 2 * std::mem::size_of::() + + 512 + + c.turn_id.capacity() + + 3 * c.session_id.capacity() + + 3 * c.agent_kind.capacity() + + c.wire_api.capacity() + + c.network_view.capacity() + + c.final_finish_reason.as_ref().map_or(0, String::capacity) + + c.primary_model.as_ref().map_or(0, String::capacity) +} +pub(crate) fn calls_bytes(calls: &[PairCandidate]) -> usize { + calls.iter().map(candidate_bytes).sum() +} +struct Cluster { + calls: Vec, + bytes: usize, + last: i64, +} +pub(crate) struct Clusters { + open: BTreeMap, + deadlines: BTreeSet<(i64, Fingerprint)>, + members: usize, + bytes: usize, + limits: Limits, +} +impl Clusters { + pub(crate) fn new(limits: Limits) -> Self { + Self { + open: BTreeMap::new(), + deadlines: BTreeSet::new(), + members: 0, + bytes: 0, + limits, + } + } + pub(crate) fn retained_bytes(&self) -> usize { + self.bytes + } + pub(crate) fn push(&mut self, c: PairCandidate) -> Result>> { + let mut closed = Vec::new(); + while self + .deadlines + .first() + .is_some_and(|(deadline, _)| *deadline < c.start_time_us) + { + let (_, key) = self.deadlines.pop_first().unwrap(); + let cluster = self.open.remove(&key).unwrap(); + self.members -= cluster.calls.len(); + self.bytes -= cluster.bytes; + closed.push(cluster.calls); + } + let bytes = candidate_bytes(&c); + if self.members >= self.limits.open_members + || self.bytes.saturating_add(bytes) > self.limits.retained_bytes + { + return Err(budget("open fingerprint clusters")); + } + let key = fingerprint(&c); + let cluster = self.open.entry(key.clone()).or_insert_with(|| Cluster { + calls: Vec::new(), + bytes: 0, + last: c.start_time_us, + }); + self.deadlines.remove(&( + cluster.last.saturating_add(MAX_REQ_TIME_GAP_US), + key.clone(), + )); + cluster.last = c.start_time_us; + cluster.bytes += bytes; + cluster.calls.push(c); + self.deadlines + .insert((cluster.last.saturating_add(MAX_REQ_TIME_GAP_US), key)); + self.members += 1; + self.bytes += bytes; + Ok(closed) + } + pub(crate) fn finish(self) -> Vec> { + self.open.into_values().map(|c| c.calls).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use h_turn::proxy_pair::{group_all, ProxyGroup}; + fn c(id: &str, session: &str, start: i64, end: i64, view: &str) -> PairCandidate { + PairCandidate { + turn_id: id.into(), + session_id: session.into(), + agent_kind: "synthetic".into(), + wire_api: "translated".into(), + start_time_us: start, + end_time_us: end, + call_count: 1, + total_input_tokens: 3, + total_output_tokens: 4, + final_finish_reason: None, + primary_model: Some(id.into()), + network_view: view.into(), + } + } + fn roles(groups: Vec) -> Vec> { + let mut groups: Vec<_> = groups + .into_iter() + .map(|g| { + let mut members: Vec<_> = g + .members + .into_iter() + .map(|m| (m.turn_id, m.role.as_str().to_owned())) + .collect(); + members.sort(); + members + }) + .collect(); + groups.sort(); + groups + } + // @scenario CLICKHOUSE-PAIR-PAGING-001 unit + #[test] + fn paged_complete_clusters_match_the_existing_classifier() { + let mut calls = vec![ + c("a", "S", 0, 1_000_000, "outer"), + c("b", "S", 90_000, 900_000, "middle"), + c("c", "S", 180_000, 800_000, "inner"), + c("same", "S", 180_000, 800_000, "outer"), + c("x", "T", 50_000, 60_000, "X"), + c("y", "T", 50_000, 60_000, "Y"), + c("ambiguous", "S", 180_000, 2_000_000, "else"), + c("next", "S", 400_001, 500_000, "next"), + ]; + calls.sort_by(|a, b| { + a.start_time_us + .cmp(&b.start_time_us) + .then_with(|| a.turn_id.cmp(&b.turn_id)) + }); + let expected = roles(group_all(&calls)); + assert!(expected.iter().any(|g| g + == &vec![ + ("a".into(), "proxy_in".into()), + ("b".into(), "proxy_out".into()), + ("c".into(), "proxy_out".into()) + ])); + for page_size in [1, 2, 3] { + let mut state = Clusters::new(Limits::default()); + let mut groups = Vec::new(); + for page in calls.chunks(page_size) { + for call in page { + for cluster in state.push(call.clone()).unwrap() { + groups.extend(group_all(&cluster)); + } + } + } + for cluster in state.finish() { + groups.extend(group_all(&cluster)); + } + assert_eq!(roles(groups), expected, "page size {page_size}"); + } + } + // @scenario CLICKHOUSE-PAIR-PAGING-001 unit + #[test] + fn an_unclosed_transitive_cluster_fails_explicitly_at_budget() { + let mut limits = Limits::default(); + limits.open_members = 2; + let mut state = Clusters::new(limits); + assert!(state + .push(c("a", "S", 0, 1_000_000, "a")) + .unwrap() + .is_empty()); + assert!(state + .push(c("b", "S", 90_000, 900_000, "b")) + .unwrap() + .is_empty()); + assert!(state + .push(c("c", "S", 180_000, 800_000, "c")) + .unwrap_err() + .to_string() + .contains("aggregation budget exceeded")); + } +} diff --git a/server/h-storage-clickhouse/src/pairing_repair.rs b/server/h-storage-clickhouse/src/pairing_repair.rs new file mode 100644 index 00000000..f5d30a6b --- /dev/null +++ b/server/h-storage-clickhouse/src/pairing_repair.rs @@ -0,0 +1,342 @@ +//! Durable original pairing patches, replayed from fresh authoritative rows. +use crate::client::{ch_err, insert_all}; +use crate::pairing::{budget, Limits}; +use crate::rows::TurnRow; +use crate::sql::{escape_str, sql_in_list}; +use crate::turns::{merge_trace_metadata, next_trace_version, now_micros, TURN_ROW_SELECT}; +use crate::ClickHouseBackend; +use clickhouse::Row; +use h_common::error::{AppError, Result}; +use h_storage::pair_sweeper::SweepStats; +use h_turn::{proxy_pair::group_all, PairCandidate}; +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +struct Target { + turn_id: String, + start_time_us: i64, + end_time_us: i64, + patch: serde_json::Value, +} +#[derive(Serialize, Deserialize)] +struct Plan { + targets: Vec, +} +#[derive(Row, Serialize, Deserialize)] +struct RepairRow { + operation_id: String, + created_at: i64, + plan: String, + _revision: u64, +} + +fn reserve_plan( + members: &[h_turn::proxy_pair::GroupMember], + group_id: &str, + limits: Limits, + resident: usize, +) -> Result<()> { + // Worst-case JSON escaping is six bytes per UTF-8 byte. Bound the repeated + // peer lists BEFORE metadata_for allocates their quadratic representation. + let ids = members.iter().try_fold(0usize, |sum, m| { + sum.checked_add(m.turn_id.len().checked_mul(6)?.checked_add(4)?) + }); + let largest = members.iter().map(|m| m.turn_id.len()).max().unwrap_or(0); + let estimate = ids + .and_then(|n| n.checked_add(512)) + .and_then(|n| n.checked_add(group_id.len().checked_mul(6)?)) + .and_then(|n| n.checked_add(largest.checked_mul(12)?)) + .and_then(|n| n.checked_mul(members.len())); + // Charge serialized text, decoded JSON objects/arrays, transient peer-list + // copies and serialization capacity together. Six-byte escaping above and + // this factor intentionally overestimate the original schema's JSON heap. + if estimate.is_none_or(|n| { + n > limits.plan_bytes + || n.checked_mul(16) + .and_then(|n| n.checked_add(resident)) + .is_none_or(|n| n > limits.retained_bytes) + }) { + return Err(budget("serialized repair plan")); + } + Ok(()) +} +fn row_bytes(r: &TurnRow) -> usize { + let strings = [ + &r.turn_id, + &r.source_id, + &r.session_id, + &r.wire_api, + &r.agent_kind, + &r.client_ip, + &r.server_ip, + &r.status, + &r.span_ids, + ]; + let optional = [ + &r.models_used, + &r.subagents_used, + &r.final_finish_reason, + &r.user_input_preview, + &r.user_call_id, + &r.final_answer_preview, + &r.final_call_id, + &r.metadata, + &r.tool_surfaces_json, + &r.agent_topology, + &r.suspicious_skills_json, + ]; + std::mem::size_of::() + + strings.into_iter().map(|s| s.capacity()).sum::() + + optional + .into_iter() + .map(|s| s.as_ref().map_or(0, String::capacity)) + .sum::() +} +fn patch_matches(row: &TurnRow, patch: &serde_json::Value) -> bool { + let current = row + .metadata + .as_deref() + .and_then(|s| serde_json::from_str::(s).ok()); + patch.as_object().is_some_and(|patch| { + patch + .iter() + .all(|(key, value)| current.as_ref().and_then(|v| v.get(key)) == Some(value)) + }) +} + +impl ClickHouseBackend { + pub(crate) async fn classify_pair_cluster( + &self, + calls: Vec, + other_bytes: usize, + stats: &mut SweepStats, + ) -> Result<()> { + // group_all retains index/assignment vectors and cloned member IDs in + // addition to the source calls. Account for that workspace before it + // allocates, alongside every still-open/closed/page-resident cohort. + let scratch = calls.len().saturating_mul(256).saturating_add( + calls + .iter() + .map(|c| c.turn_id.capacity().saturating_mul(2)) + .sum::(), + ); + let resident = other_bytes + .saturating_add(crate::pairing_groups::calls_bytes(&calls)) + .saturating_add(scratch); + if resident > self.pairing_limits.retained_bytes { + return Err(budget("classifier workspace")); + } + for group in group_all(&calls) { + reserve_plan( + &group.members, + &group.group_id, + self.pairing_limits, + resident, + )?; + let targets = group + .members + .iter() + .map(|m| { + let c = calls + .iter() + .find(|c| c.turn_id == m.turn_id) + .expect("classifier member exists"); + Target { + turn_id: m.turn_id.clone(), + start_time_us: c.start_time_us, + end_time_us: c.end_time_us, + patch: group + .metadata_for(&m.turn_id) + .expect("classifier member patch"), + } + }) + .collect(); + let plan = serde_json::to_string(&Plan { targets }) + .map_err(|e| AppError::Storage(format!("serialize pairing plan: {e}")))?; + if plan.len() > self.pairing_limits.plan_bytes { + return Err(budget("serialized repair plan")); + } + let row = RepairRow { + operation_id: group.group_id, + created_at: now_micros() as i64, + plan, + _revision: 1, + }; + let mut insert = self + .client + .insert::("trace_pair_repairs") + .await + .map_err(|e| ch_err("pairing intent insert", e))?; + insert + .write(&row) + .await + .map_err(|e| ch_err("pairing intent write", e))?; + insert + .end() + .await + .map_err(|e| ch_err("pairing intent commit", e))?; + #[cfg(test)] + if self + .pairing_faults + .after_plan_ack + .swap(false, std::sync::atomic::Ordering::SeqCst) + { + return Err(AppError::Storage( + "synthetic lost pairing intent acknowledgement".into(), + )); + } + self.apply_pair_plan(row, resident, stats).await?; + } + Ok(()) + } + + pub(crate) async fn replay_pair_repairs(&self, stats: &mut SweepStats) -> Result<()> { + loop { + let row=self.client.query("SELECT operation_id,created_at,plan,_revision FROM trace_pair_repairs FINAL ORDER BY operation_id ASC LIMIT 1 SETTINGS max_threads=1,max_memory_usage=268435456") + .fetch_optional::().await.map_err(|e|ch_err("pending pairing intent",e))?; + let Some(row) = row else { break }; + self.apply_pair_plan(row, 0, stats).await?; + } + Ok(()) + } + + async fn apply_pair_plan( + &self, + row: RepairRow, + other_bytes: usize, + stats: &mut SweepStats, + ) -> Result<()> { + if row.plan.len() > self.pairing_limits.plan_bytes { + return Err(budget("stored repair plan")); + } + let resident = row + .plan + .capacity() + .saturating_mul(16) + .saturating_add(other_bytes); + if resident > self.pairing_limits.retained_bytes { + return Err(budget("stored repair plan heap")); + } + let write_bytes = self + .pairing_limits + .write_bytes + .min(self.pairing_limits.retained_bytes - resident); + let plan: Plan = serde_json::from_str(&row.plan) + .map_err(|e| AppError::Storage(format!("invalid stored pairing intent: {e}")))?; + for targets in plan.targets.chunks(self.pairing_limits.write_rows) { + let ids: Vec<_> = targets.iter().map(|t| t.turn_id.clone()).collect(); + let sql=format!("SELECT {TURN_ROW_SELECT} FROM traces FINAL WHERE turn_id IN ({}) ORDER BY turn_id ASC SETTINGS max_threads=1,max_memory_usage=268435456",sql_in_list(&ids)); + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("pairing authoritative read", e))?; + let mut rows = Vec::new(); + let mut bytes = 0usize; + while let Some(mut current) = stream + .next() + .await + .map_err(|e| ch_err("pairing authoritative row", e))? + { + let target = targets + .iter() + .find(|t| t.turn_id == current.turn_id) + .expect("requested target"); + if patch_matches(¤t, &target.patch) { + continue; + } + current.metadata = Some(merge_trace_metadata( + current.metadata.as_deref(), + &target.patch, + )); + current._version = next_trace_version(current._version, now_micros())?; + let current_bytes = row_bytes(¤t); + if !rows.is_empty() && bytes.saturating_add(current_bytes) > write_bytes { + stats.turns_tagged += rows.len(); + self.commit_pair_rows(std::mem::take(&mut rows)).await?; + bytes = 0; + } + bytes = bytes.saturating_add(current_bytes); + rows.push(current); + // A single indivisible stored row may exceed the soft byte + // target. It is streamed alone, without truncating its content. + if bytes >= write_bytes { + stats.turns_tagged += rows.len(); + self.commit_pair_rows(std::mem::take(&mut rows)).await?; + bytes = 0; + } + } + if !rows.is_empty() { + stats.turns_tagged += rows.len(); + self.commit_pair_rows(rows).await?; + } + } + // Verify surviving targets from fresh rows. Missing targets were deleted + // or never stored; do not resurrect them or count them as tagged. + for targets in plan.targets.chunks(self.pairing_limits.write_rows) { + let ids: Vec<_> = targets.iter().map(|t| t.turn_id.clone()).collect(); + let sql=format!("SELECT {TURN_ROW_SELECT} FROM traces FINAL WHERE turn_id IN ({}) ORDER BY turn_id ASC SETTINGS max_threads=1,max_memory_usage=268435456",sql_in_list(&ids)); + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("pairing verification read", e))?; + while let Some(current) = stream + .next() + .await + .map_err(|e| ch_err("pairing verification row", e))? + { + let target = targets + .iter() + .find(|t| t.turn_id == current.turn_id) + .expect("requested target"); + if !patch_matches(¤t, &target.patch) { + return Err(AppError::Storage( + "pairing metadata verification failed; original intent retained".into(), + )); + } + } + } + #[cfg(test)] + if self + .pairing_faults + .before_plan_delete + .swap(false, std::sync::atomic::Ordering::SeqCst) + { + return Err(AppError::Storage( + "synthetic lost pairing completion acknowledgement".into(), + )); + } + self.exec(&format!("ALTER TABLE trace_pair_repairs DELETE WHERE operation_id='{}' SETTINGS mutations_sync=1",escape_str(&row.operation_id))).await?; + stats.pairs_assigned += 1; + Ok(()) + } + + async fn commit_pair_rows(&self, rows: Vec) -> Result<()> { + insert_all!(self.client, "traces", TurnRow, rows); + #[cfg(test)] + self.pairing_faults.trace_chunk()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + // @scenario CLICKHOUSE-PAIR-REPAIR-001 unit + #[test] + fn peer_patch_explosion_is_rejected_before_allocating_peer_lists() { + let members = (0..1000) + .map(|i| h_turn::proxy_pair::GroupMember { + turn_id: format!("synthetic-member-{i}"), + role: h_turn::proxy_pair::ProxyRole::ProxyOut, + }) + .collect::>(); + let limits = Limits::default(); + assert!(reserve_plan(&members, "synthetic-group", limits, 0) + .unwrap_err() + .to_string() + .contains("aggregation budget exceeded")); + assert!(reserve_plan(&members[..2], "synthetic-group", limits, 0).is_ok()); + } +} diff --git a/server/h-storage-clickhouse/src/pairing_tests.rs b/server/h-storage-clickhouse/src/pairing_tests.rs new file mode 100644 index 00000000..54b7401c --- /dev/null +++ b/server/h-storage-clickhouse/src/pairing_tests.rs @@ -0,0 +1,1193 @@ +//! ClickHouse pairing/versioning regressions, exercised against a real server. +use crate::it::fixtures::sample_turn; +use clickhouse::Row; +use serde::Deserialize; + +// @scenario CLICKHOUSE-PAIR-VERSION-001 integration +#[tokio::test] +async fn metadata_version_must_increase_even_when_source_clock_is_ahead() { + let Some(backend) = crate::it::fresh_backend("heron_it_pair_future_version").await else { + return; + }; + let mut trace = sample_turn( + "synthetic-future-turn", + "synthetic-session", + 1_000_000, + vec![], + ); + trace.client_ip = "192.0.2.1".parse().unwrap(); + trace.server_ip = "192.0.2.2".parse().unwrap(); + trace.metadata = serde_json::json!({"keep":"synthetic-unrelated-value"}); + backend.write_traces(vec![trace]).await.unwrap(); + backend.exec("INSERT INTO traces SELECT * REPLACE(toUInt64(18446744073709551614) AS _version) FROM traces FINAL").await.unwrap(); + backend + .update_trace_metadata( + "synthetic-future-turn", + serde_json::json!({"proxy":{"role":"proxy_in","pair_id":"synthetic-stable-group"}}), + ) + .await + .unwrap(); + #[derive(Row, Deserialize)] + struct Actual { + metadata: Option, + version: u64, + } + let row = backend.client.query("SELECT metadata,_version AS version FROM traces FINAL WHERE turn_id='synthetic-future-turn'") + .fetch_one::().await.unwrap(); + let metadata: serde_json::Value = + serde_json::from_str(row.metadata.as_deref().unwrap()).unwrap(); + assert_eq!( + metadata["proxy"]["pair_id"], "synthetic-stable-group", + "new metadata cannot lose to a future source version" + ); + assert_eq!(metadata["keep"], "synthetic-unrelated-value"); + assert_eq!(row.version, u64::MAX); + let overflow = backend + .update_trace_metadata("synthetic-future-turn", serde_json::json!({"extra":true})) + .await; + assert!( + overflow.is_err(), + "source-version exhaustion must fail explicitly" + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_future_version") + .execute() + .await + .unwrap(); +} + +fn synthetic_trace(id: &str, session: &str, start: i64, end: i64, view: u8) -> h_turn::Trace { + let mut trace = sample_turn(id, session, start, vec![]); + trace.end_time_us = end; + trace.client_ip = std::net::Ipv4Addr::new(192, 0, 2, view).into(); + trace.server_ip = "192.0.2.254".parse().unwrap(); + trace.metadata = serde_json::json!({"keep":"original"}); + trace +} + +#[derive(Row, Deserialize)] +struct PairScan { + query: String, + result_rows: u64, + read_rows: u64, + read_bytes: u64, + result_bytes: u64, + query_duration_ms: u64, +} + +fn require_pair_scan_evidence(init: &[PairScan], warm: &[PairScan]) -> Result<(), &'static str> { + if init.is_empty() || !init.iter().any(|s| s.query.contains("FROM traces FINAL")) { + return Err("initialization backfill was not measured"); + } + if warm.len() != 8 + || warm.iter().map(|s| s.read_rows).sum::() == 0 + || warm.iter().map(|s| s.read_bytes).sum::() == 0 + { + return Err("warmed SELECT measurement is absent or incomplete"); + } + let pages: Vec<_> = warm + .iter() + .filter(|s| s.query.contains("FROM trace_pair_candidates FINAL")) + .collect(); + if pages.iter().map(|s| s.result_rows).collect::>() != [32, 32, 32, 4, 0] { + return Err("candidate measurement lacks the complete 100-row page walk and empty tail"); + } + if pages[0].query.contains("(start_time,turn_id)>") { + return Err("first measured candidate page unexpectedly has a cursor"); + } + for (page, id) in + pages[1..] + .iter() + .zip(["recent-031", "recent-063", "recent-095", "recent-099"]) + { + if !page.query.contains("(start_time,turn_id)>") || !page.query.contains(id) { + return Err("candidate continuation cursor was not measured"); + } + } + Ok(()) +} + +#[test] +fn pairing_scan_evidence_rejects_missing_logs_and_empty_tail() { + let record = |query: &str, result_rows| PairScan { + query: query.into(), + result_rows, + read_rows: 1, + read_bytes: 1, + result_bytes: 1, + query_duration_ms: 0, + }; + let init = [record("SELECT ... FROM traces FINAL", 100)]; + let mut warm = vec![ + record("SELECT ... FROM system.tables", 4), + record("SELECT ... FROM trace_pair_index_state FINAL", 1), + record("SELECT ... FROM trace_pair_repairs FINAL", 0), + record("SELECT ... FROM trace_pair_candidates FINAL", 32), + ]; + for (id, rows) in [ + ("recent-031", 32), + ("recent-063", 32), + ("recent-095", 4), + ("recent-099", 0), + ] { + warm.push(record(&format!("SELECT ... FROM trace_pair_candidates FINAL WHERE (start_time,turn_id)> ... '{id}'"),rows)); + } + assert!(require_pair_scan_evidence(&init, &warm).is_ok()); + assert!(require_pair_scan_evidence(&[], &warm).is_err()); + assert!(require_pair_scan_evidence(&init, &[]).is_err()); + let tail = warm.pop().unwrap(); + assert!(require_pair_scan_evidence(&init, &warm).is_err()); + warm.push(tail); + warm.last_mut().unwrap().result_rows = 4; + assert!(require_pair_scan_evidence(&init, &warm).is_err()); + warm.last_mut().unwrap().result_rows = 0; + warm.last_mut().unwrap().query = "SELECT ... FROM trace_pair_candidates FINAL".into(); + assert!(require_pair_scan_evidence(&init, &warm).is_err()); +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_production_sweep_scan_does_not_grow_with_old_history() { + use h_storage::StorageBackend; + use std::sync::Arc; + use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let mut samples = Vec::new(); + for history in [0, 100_000, 500_000] { + let db = format!("heron_it_pair_scan_{history}"); + let Some(mut backend) = crate::it::fresh_backend(&db).await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.page_rows = 32; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_micros() as i64; + backend.exec(&format!("INSERT INTO traces (turn_id,session_id,agent_kind,wire_api,start_time,end_time,call_count,total_input_tokens,total_output_tokens,client_ip,server_ip,_version) SELECT concat('old-',toString(number)),concat('old-session-',toString(number)),'synthetic','openai-chat',fromUnixTimestamp64Micro(toInt64(number)),fromUnixTimestamp64Micro(toInt64(number+1)),1,1,1,'192.0.2.1','192.0.2.2',toUInt64(number+1) FROM numbers({history}) SETTINGS max_threads=1")).await.unwrap(); + backend + .write_traces( + (0..100) + .map(|i| { + synthetic_trace( + &format!("recent-{i:03}"), + &format!("recent-session-{i}"), + now - 1_000_000 + i, + now - 500_000 + i, + 1, + ) + }) + .collect(), + ) + .await + .unwrap(); + backend.exec("OPTIMIZE TABLE traces FINAL").await.unwrap(); + // First actual sweep includes one-time index initialization; isolate it + // from the warmed recurring path, never substitute a manual SELECT. + let init_id = format!("pair-init-{history}-{nonce}"); + backend.client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", init_id.clone()) + .with_setting("max_threads", "1"); + let storage = Arc::new(backend); + let dyn_storage: Arc = storage.clone(); + let init_start = Instant::now(); + let initial = h_storage::pair_sweeper::sweep_once(&dyn_storage, Duration::from_secs(1800)) + .await + .unwrap(); + let init_us = init_start.elapsed().as_micros(); + assert_eq!(initial.candidates_scanned, 100); + // Rebuild the backend (same DB) so ready state also proves restart reuse. + let cfg = h_common::config::ClickHouseConfig { + url: storage.url.clone(), + database: db.clone(), + user: storage.user.clone(), + password: storage.password.clone(), + optimize_on_sweep: false, + }; + let mut warm = crate::ClickHouseBackend::new(&cfg).unwrap(); + warm.pairing_limits.page_rows = 32; + let warm_id = format!("pair-warm-{history}-{nonce}"); + warm.client = warm + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", warm_id.clone()) + .with_setting("max_threads", "1"); + let warm: Arc = Arc::new(warm); + let start = Instant::now(); + let stats = h_storage::pair_sweeper::sweep_once(&warm, Duration::from_secs(1800)) + .await + .unwrap(); + let elapsed = start.elapsed().as_micros(); + assert_eq!( + stats, + h_storage::pair_sweeper::SweepStats { + candidates_scanned: 100, + pairs_assigned: 0, + turns_tagged: 0 + } + ); + let admin = storage.admin_client(); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let scans=admin.query(&format!("SELECT query,result_rows,read_rows,read_bytes,result_bytes,query_duration_ms FROM system.query_log WHERE current_database='{db}' AND type='QueryFinish' AND query_id='{warm_id}' AND startsWith(query,'SELECT') ORDER BY event_time_microseconds,query" )).fetch_all::().await.unwrap(); + let init=admin.query(&format!("SELECT query,result_rows,read_rows,read_bytes,result_bytes,query_duration_ms FROM system.query_log WHERE current_database='{db}' AND type='QueryFinish' AND query_id='{init_id}' AND startsWith(query,'SELECT')")).fetch_all::().await.unwrap(); + let evidence = require_pair_scan_evidence(&init, &scans); + let reads = scans.iter().map(|s| s.read_rows).sum::(); + let bytes = scans.iter().map(|s| s.read_bytes).sum::(); + eprintln!("pair production scan history={history} recent=100 init_rows={} init_bytes={} init_client_us={init_us} warm_rows={reads} warm_bytes={bytes} result_bytes={} server_ms={} client_us={elapsed} queries={}",init.iter().map(|s|s.read_rows).sum::(),init.iter().map(|s|s.read_bytes).sum::(),scans.iter().map(|s|s.result_bytes).sum::(),scans.iter().map(|s|s.query_duration_ms).sum::(),scans.len()); + for s in &scans { + eprintln!( + "pair query rows={} bytes={} sql={}", + s.read_rows, s.read_bytes, s.query + ); + } + samples.push((history, reads, bytes)); + admin + .query(&format!("DROP DATABASE `{db}`")) + .execute() + .await + .unwrap(); + evidence.expect("production scan measurement is missing initialization or complete warmed page evidence"); + } + assert_eq!(samples.len(), 3); + for sample in &samples[1..] { + assert!( + sample.1 <= samples[0].1 + 65_536, + "recurring sweep SELECTs scanned retained history: {samples:?}" + ); + assert!( + sample.2 <= samples[0].2 + 8 * 1024 * 1024, + "recurring sweep SELECT bytes grew with retained history: {samples:?}" + ); + } +} + +pub(crate) struct Faults { + pub(crate) after_trace_chunks: std::sync::atomic::AtomicIsize, + pub(crate) after_plan_ack: std::sync::atomic::AtomicBool, + pub(crate) after_backfill_page: std::sync::atomic::AtomicBool, + pub(crate) before_plan_delete: std::sync::atomic::AtomicBool, +} +impl Default for Faults { + fn default() -> Self { + Self { + after_trace_chunks: std::sync::atomic::AtomicIsize::new(-1), + after_plan_ack: std::sync::atomic::AtomicBool::new(false), + after_backfill_page: std::sync::atomic::AtomicBool::new(false), + before_plan_delete: std::sync::atomic::AtomicBool::new(false), + } + } +} +impl Faults { + pub(crate) fn trace_chunk(&self) -> h_common::error::Result<()> { + use std::sync::atomic::Ordering; + if self.after_trace_chunks.load(Ordering::SeqCst) > 0 + && self.after_trace_chunks.fetch_sub(1, Ordering::SeqCst) == 1 + { + return Err(h_common::error::AppError::Storage( + "synthetic failure after committed metadata chunk".into(), + )); + } + Ok(()) + } +} + +fn reconnect(backend: &crate::ClickHouseBackend) -> crate::ClickHouseBackend { + crate::ClickHouseBackend::new(&h_common::config::ClickHouseConfig { + url: backend.url.clone(), + user: backend.user.clone(), + password: backend.password.clone(), + database: backend.database.clone(), + optimize_on_sweep: false, + }) + .unwrap() +} + +#[derive(Row, Deserialize)] +struct MetadataRow { + turn_id: String, + metadata: Option, + version: u64, +} +async fn metadata_rows(backend: &crate::ClickHouseBackend) -> Vec { + backend + .client + .query("SELECT turn_id,metadata,_version AS version FROM traces FINAL ORDER BY turn_id") + .fetch_all::() + .await + .unwrap() +} + +// @scenario CLICKHOUSE-PAIR-REPAIR-001 integration +#[tokio::test] +async fn pairing_partial_write_restart_keeps_original_group_and_outside_window_members() { + use h_storage::StorageBackend; + use std::sync::{atomic::Ordering, Arc}; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_partial").await else { + return; + }; + backend.summary_worker.stop(); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_micros() as i64; + backend + .write_traces(vec![ + synthetic_trace("a", "same", now - 1_000_000, now - 1000, 1), + synthetic_trace("b", "same", now - 990_000, now - 2000, 2), + synthetic_trace("c", "same", now - 980_000, now - 3000, 3), + ]) + .await + .unwrap(); + backend.pairing_limits.write_rows = 1; + backend + .pairing_faults + .after_trace_chunks + .store(1, Ordering::SeqCst); + let backend = Arc::new(backend); + let storage: Arc = backend.clone(); + let first = h_storage::pair_sweeper::sweep_once(&storage, Duration::from_secs(1800)).await; + assert!( + first.is_err(), + "real first metadata chunk must commit before synthetic failure" + ); + let rows = metadata_rows(&backend).await; + let paired: Vec<_> = rows + .iter() + .filter_map(|r| { + serde_json::from_str::(r.metadata.as_deref()?) + .ok() + .filter(|v| v["proxy"]["pair_id"].is_string()) + }) + .collect(); + assert!( + !paired.is_empty(), + "partial metadata write must actually persist" + ); + let original = paired[0]["proxy"]["pair_id"].clone(); + let restarted = Arc::new(reconnect(&backend)); + let restarted_storage: Arc = restarted.clone(); + // All three original targets are now outside this discovery window. + let repair = h_storage::pair_sweeper::sweep_once(&restarted_storage, Duration::from_micros(1)) + .await + .unwrap(); + let rows = metadata_rows(&restarted).await; + let actual: Vec<_> = rows + .iter() + .map(|r| serde_json::from_str::(r.metadata.as_deref().unwrap()).unwrap()) + .collect(); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_partial") + .execute() + .await + .unwrap(); + assert_eq!( + repair.pairs_assigned, 1, + "pending intent survives restart and window aging" + ); + for metadata in actual { + assert_eq!( + metadata["proxy"]["pair_id"], original, + "repair must replay original group for every target" + ); + assert_eq!(metadata["keep"], "original"); + } +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +// @scenario CLICKHOUSE-PAIR-PAGING-001 integration +#[tokio::test] +async fn pairing_index_preserves_latest_versions_and_equal_time_keyset_order() { + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_index").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.page_rows = 2; + backend.exec("SYSTEM STOP MERGES traces").await.unwrap(); + backend + .exec("SYSTEM STOP MERGES trace_pair_candidates") + .await + .unwrap(); + backend + .write_traces( + ["a", "b", "c", "d", "e"] + .into_iter() + .map(|id| synthetic_trace(id, id, 100, 1000, 1)) + .collect(), + ) + .await + .unwrap(); + backend.exec("INSERT INTO traces SELECT * REPLACE(toUInt64(5000) AS _version,'{\"proxy\":{\"role\":\"proxy_in\"}}' AS metadata) FROM traces FINAL WHERE turn_id='a'").await.unwrap(); + backend.exec("INSERT INTO traces SELECT * REPLACE(toUInt64(1001) AS _version,'{}' AS metadata) FROM traces FINAL WHERE turn_id='a'").await.unwrap(); + let ids: Vec<_> = backend + .query_pair_candidates(0, 2000) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + assert_eq!(ids, ["b", "c", "d", "e"]); + let copies = crate::it::count(&backend, "trace_pair_candidates").await; + assert!( + copies > 5, + "unmerged all-version MV/backfill must retain overlap" + ); + #[derive(Row, Deserialize)] + struct Version { + version: u64, + role: String, + } + let latest=backend.client.query("SELECT _version AS version,proxy_role AS role FROM trace_pair_candidates FINAL WHERE turn_id='a'").fetch_one::().await.unwrap(); + assert_eq!(latest.version, 5000); + assert_eq!(latest.role, "proxy_in"); + backend.exec("SYSTEM START MERGES traces").await.unwrap(); + backend + .exec("SYSTEM START MERGES trace_pair_candidates") + .await + .unwrap(); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_index") + .execute() + .await + .unwrap(); +} + +async fn state_revision(backend: &crate::ClickHouseBackend) -> u64 { + backend + .client + .query("SELECT _revision FROM trace_pair_index_state FINAL WHERE job='initialize'") + .fetch_one::() + .await + .unwrap() +} +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_ready_index_widens_existing_history_and_recovers_recreated_objects() { + let Some(backend) = crate::it::fresh_backend("heron_it_pair_coverage").await else { + return; + }; + backend.summary_worker.stop(); + // These rows predate the MV. A ready marker must not claim their entire + // history when the initial fixed backfill covered only the recent row. + backend + .exec("DROP TABLE trace_pair_candidates_mv") + .await + .unwrap(); + backend + .write_traces(vec![ + synthetic_trace("old", "old", 100, 150, 1), + synthetic_trace("recent", "recent", 600, 700, 1), + ]) + .await + .unwrap(); + assert_eq!( + backend + .query_pair_candidates(500, 1000) + .await + .unwrap() + .len(), + 1 + ); + // A disjoint older compatibility window must not leave a pre-view gap + // between its upper bound and the original lower bound. + let older = reconnect(&backend); + assert!(older.query_pair_candidates(0, 50).await.unwrap().is_empty()); + let restarted = reconnect(&backend); + let ids: Vec<_> = restarted + .query_pair_candidates(0, 1000) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + assert_eq!(ids, ["old", "recent"]); + let ready_revision = state_revision(&restarted).await; + let forward = reconnect(&backend); + assert_eq!( + forward + .query_pair_candidates(500, 1100) + .await + .unwrap() + .len(), + 1 + ); + assert_eq!( + state_revision(&forward).await, + ready_revision, + "covered restarts must not repeat backfill" + ); + let mut expected = 2; + for object in ["trace_pair_candidates_mv", "trace_pair_candidates"] { + forward.exec(&format!("DROP TABLE {object}")).await.unwrap(); + assert_eq!( + forward.query_pair_candidates(0, 1100).await.unwrap().len(), + expected, + "rebuild {object}" + ); + expected += 1; + let id = format!("after-{object}"); + forward + .write_traces(vec![synthetic_trace(&id, &id, 800, 900, 2)]) + .await + .unwrap(); + assert!( + forward + .query_pair_candidates(750, 1000) + .await + .unwrap() + .iter() + .any(|c| c.turn_id == id), + "MV must target the rebuilt destination" + ); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_coverage") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_ordinary_recovery_replays_history_and_reuses_ready_generation() { + let db = "heron_it_pair_ordinary"; + let Some(backend) = crate::it::fresh_backend(db).await else { + return; + }; + backend.summary_worker.stop(); + let admin = backend.admin_client(); + let mut recovered = Vec::new(); + for case in ["candidate", "view", "legacy"] { + admin + .query(&format!("DROP DATABASE `{db}`")) + .execute() + .await + .unwrap(); + admin + .clone() + .with_setting("allow_deprecated_database_ordinary", "1") + .query(&format!("CREATE DATABASE `{db}` ENGINE=Ordinary")) + .execute() + .await + .unwrap(); + crate::schema::init(&backend).await.unwrap(); + let uuids = backend.client.query("SELECT toString(uuid) FROM system.tables WHERE database=currentDatabase() AND name IN ('trace_pair_candidates','trace_pair_candidates_mv') ORDER BY name") + .fetch_all::().await.unwrap(); + assert_eq!(uuids, ["00000000-0000-0000-0000-000000000000"; 2]); + backend + .write_traces(vec![synthetic_trace("original", "original", 100, 200, 1)]) + .await + .unwrap(); + assert_eq!( + backend.query_pair_candidates(0, 1000).await.unwrap()[0].turn_id, + "original" + ); + match case { + "candidate" => backend + .exec("DROP TABLE trace_pair_candidates") + .await + .unwrap(), + "view" => { + backend + .exec("DROP TABLE trace_pair_candidates_mv") + .await + .unwrap(); + backend + .write_traces(vec![synthetic_trace("gap", "gap", 300, 400, 2)]) + .await + .unwrap(); + } + "legacy" => { + // A pre-upgrade zero-ID ready marker must not certify an empty + // candidate table, even with both untagged objects still present. + backend + .exec("TRUNCATE TABLE trace_pair_candidates") + .await + .unwrap(); + for object in ["trace_pair_candidates", "trace_pair_candidates_mv"] { + backend + .exec(&format!( + "ALTER TABLE {object} MODIFY COMMENT 'operator\\'s note\\nkeep this'" + )) + .await + .unwrap(); + } + backend.exec("INSERT INTO trace_pair_index_state SELECT * REPLACE('00000000-0000-0000-0000-000000000000' AS destination_id,'00000000-0000-0000-0000-000000000000' AS view_id,_revision+1 AS _revision) FROM trace_pair_index_state FINAL WHERE job='initialize'").await.unwrap(); + } + _ => unreachable!(), + } + // Exercise recovery without init() and again after startup init(). + let restarted = reconnect(&backend); + let ids: Vec<_> = restarted + .query_pair_candidates(0, 1000) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + recovered.push((case, ids)); + let revision = state_revision(&restarted).await; + let identities = restarted.client.query("SELECT destination_id,view_id FROM trace_pair_index_state FINAL WHERE job='initialize'") + .fetch_one::<(String, String)>().await.unwrap(); + let comments = restarted.client.query("SELECT comment FROM system.tables WHERE database=currentDatabase() AND name IN ('trace_pair_candidates','trace_pair_candidates_mv') ORDER BY name") + .fetch_all::().await.unwrap(); + let mut warm = reconnect(&backend); + let query_id = format!("ordinary-warm-{case}-{}", uuid::Uuid::now_v7()); + warm.client = warm + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", query_id.clone()); + for _ in 0..2 { + crate::schema::init(&warm).await.unwrap(); + let warm_ids: Vec<_> = warm + .query_pair_candidates(0, 1000) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + assert_eq!(warm_ids, recovered.last().unwrap().1); + } + assert_eq!( + state_revision(&warm).await, + revision, + "ready generation must survive repeated init and restart" + ); + assert_eq!(warm.client.query("SELECT destination_id,view_id FROM trace_pair_index_state FINAL WHERE job='initialize'") + .fetch_one::<(String, String)>().await.unwrap(), identities); + assert_eq!(warm.client.query("SELECT comment FROM system.tables WHERE database=currentDatabase() AND name IN ('trace_pair_candidates','trace_pair_candidates_mv') ORDER BY name") + .fetch_all::().await.unwrap(), comments); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let repeated_work = admin.query(&format!("SELECT count() FROM system.query_log WHERE current_database='{db}' AND query_id='{query_id}' AND type='QueryFinish' AND (position(query,'MODIFY COMMENT')>0 OR (startsWith(query,'SELECT') AND position(query,'FROM traces')>0) OR startsWith(query,'INSERT'))")) + .fetch_one::().await.unwrap(); + assert_eq!( + repeated_work, 0, + "Ordinary warm reuse must not retag or scan history" + ); + if case == "legacy" { + // Check preservation only after recording the recovery result, so + // the original regression fails on lost IDs rather than comments. + assert!(comments + .iter() + .all(|comment| comment.starts_with("operator's note\nkeep this"))); + } + } + admin + .query(&format!("DROP DATABASE `{db}`")) + .execute() + .await + .unwrap(); + assert_eq!( + recovered, + [ + ("candidate", vec!["original".to_string()]), + ("view", vec!["original".to_string(), "gap".to_string()]), + ("legacy", vec!["original".to_string()]), + ], + "Ordinary object recovery must replay authoritative candidate IDs" + ); +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_backfill_resumes_fixed_bounds_after_insert_before_cursor_ack() { + use std::sync::atomic::Ordering; + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_resume").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.page_rows = 2; + backend + .exec("DROP TABLE trace_pair_candidates_mv") + .await + .unwrap(); + backend + .write_traces( + (0..5) + .map(|i| { + synthetic_trace( + &format!("id-{i}"), + &format!("session-{i}"), + 100 + i, + 200 + i, + 1, + ) + }) + .collect(), + ) + .await + .unwrap(); + backend + .pairing_faults + .after_backfill_page + .store(true, Ordering::SeqCst); + assert!(backend.query_pair_candidates(0, 500).await.is_err()); + backend + .write_traces(vec![synthetic_trace( + "concurrent", + "concurrent", + 300, + 400, + 2, + )]) + .await + .unwrap(); + backend + .update_trace_metadata( + "id-0", + serde_json::json!({"proxy":{"role":"proxy_in","pair_id":"already-paired"}}), + ) + .await + .unwrap(); + let restarted = reconnect(&backend); + let ids: Vec<_> = restarted + .query_pair_candidates(0, 1000) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + assert_eq!(ids, ["id-1", "id-2", "id-3", "id-4", "concurrent"]); + #[derive(Row, Deserialize)] + struct Bounds { + lo: i64, + hi: i64, + ready: u8, + } + let state = restarted + .client + .query("SELECT lo,hi,ready FROM trace_pair_index_state FINAL WHERE job='initialize'") + .fetch_one::() + .await + .unwrap(); + assert_eq!( + (state.lo, state.hi, state.ready), + (0, 500, 1), + "resume original bounds, later inserts covered by MV" + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_resume") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-PAIR-PAGING-001 integration +#[tokio::test] +async fn pairing_transitive_cluster_crosses_pages_and_late_unmatched_rows_are_revisited() { + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_pages").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.page_rows = 1; + backend + .write_traces(vec![ + synthetic_trace("a", "same", 100, 1_000_000, 1), + synthetic_trace("b", "same", 90_100, 900_000, 2), + synthetic_trace("c", "same", 180_100, 800_000, 3), + ]) + .await + .unwrap(); + let first = backend.sweep_pair_window(0, 2_000_000).await.unwrap(); + assert_eq!( + ( + first.candidates_scanned, + first.pairs_assigned, + first.turns_tagged + ), + (3, 1, 3) + ); + let rows = metadata_rows(&backend).await; + for (i, row) in rows.iter().enumerate() { + let m: serde_json::Value = serde_json::from_str(row.metadata.as_deref().unwrap()).unwrap(); + assert_eq!( + m["proxy"]["role"], + if i == 0 { "proxy_in" } else { "proxy_out" } + ); + assert_eq!(m["proxy"]["peer_turn_ids"].as_array().unwrap().len(), 2); + } + backend + .write_traces(vec![synthetic_trace( + "late-alone", + "late", + 500_000, + 700_000, + 1, + )]) + .await + .unwrap(); + assert_eq!( + backend + .sweep_pair_window(0, 2_000_000) + .await + .unwrap() + .pairs_assigned, + 0 + ); + backend + .write_traces(vec![synthetic_trace( + "late-earlier", + "late", + 499_000, + 701_000, + 2, + )]) + .await + .unwrap(); + assert_eq!( + backend + .sweep_pair_window(0, 2_000_000) + .await + .unwrap() + .pairs_assigned, + 1 + ); + // A new singleton after a successful group is not a feature request to + // reopen/coalesce that historical successful cohort. + backend + .write_traces(vec![synthetic_trace( + "new-alone", + "same", + 190_100, + 750_000, + 4, + )]) + .await + .unwrap(); + let final_stats = backend.sweep_pair_window(0, 2_000_000).await.unwrap(); + assert_eq!( + ( + final_stats.candidates_scanned, + final_stats.pairs_assigned, + final_stats.turns_tagged + ), + (1, 0, 0) + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_pages") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-PAIR-REPAIR-001 integration +#[tokio::test] +async fn pairing_original_journal_survives_plan_ack_loss_and_completion_ack_loss() { + use std::sync::atomic::Ordering; + for completion_loss in [false, true] { + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_ack").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.write_rows = 1; + backend + .write_traces(vec![ + synthetic_trace("a", "same", 100, 1000, 1), + synthetic_trace("b", "same", 200, 900, 2), + ]) + .await + .unwrap(); + if completion_loss { + backend + .pairing_faults + .before_plan_delete + .store(true, Ordering::SeqCst); + } else { + backend + .pairing_faults + .after_plan_ack + .store(true, Ordering::SeqCst); + } + assert!(backend.sweep_pair_window(0, 2000).await.is_err()); + let original_id = backend + .client + .query("SELECT operation_id FROM trace_pair_repairs FINAL") + .fetch_one::() + .await + .unwrap(); + let before = metadata_rows(&backend).await; + let restarted = reconnect(&backend); + let stats = restarted.sweep_pair_window(10_000, 20_000).await.unwrap(); + assert_eq!(stats.pairs_assigned, 1); + assert_eq!(stats.turns_tagged, if completion_loss { 0 } else { 2 }); + let after = metadata_rows(&backend).await; + for row in &after { + let m: serde_json::Value = + serde_json::from_str(row.metadata.as_deref().unwrap()).unwrap(); + assert_eq!(m["proxy"]["pair_id"], original_id); + } + if completion_loss { + assert_eq!( + before + .iter() + .map(|r| (&r.turn_id, r.version)) + .collect::>(), + after + .iter() + .map(|r| (&r.turn_id, r.version)) + .collect::>() + ); + } + assert_eq!( + crate::it::count(&backend, "trace_pair_repairs FINAL").await, + 0 + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_ack") + .execute() + .await + .unwrap(); + } +} + +// @scenario CLICKHOUSE-PAIR-REPAIR-001 integration +#[tokio::test] +async fn pairing_repair_skips_deleted_target_and_preserves_fresh_unrelated_metadata() { + use std::sync::atomic::Ordering; + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_deleted").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.write_rows = 1; + backend + .write_traces(vec![ + synthetic_trace("a", "same", 100, 1000, 1), + synthetic_trace("b", "same", 200, 900, 2), + synthetic_trace("c", "same", 300, 800, 3), + ]) + .await + .unwrap(); + backend + .pairing_faults + .after_trace_chunks + .store(1, Ordering::SeqCst); + assert!(backend.sweep_pair_window(0, 2000).await.is_err()); + let original = backend + .client + .query("SELECT operation_id FROM trace_pair_repairs FINAL") + .fetch_one::() + .await + .unwrap(); + backend + .update_trace_metadata("b", serde_json::json!({"new-key":"fresh value"})) + .await + .unwrap(); + let before_b = metadata_rows(&backend) + .await + .into_iter() + .find(|r| r.turn_id == "b") + .unwrap() + .version; + backend + .exec("ALTER TABLE traces DELETE WHERE turn_id='c' SETTINGS mutations_sync=1") + .await + .unwrap(); + let restarted = reconnect(&backend); + let stats = restarted.sweep_pair_window(3000, 4000).await.unwrap(); + assert_eq!(stats.turns_tagged, 1); + assert_eq!(stats.pairs_assigned, 1); + let rows = metadata_rows(&backend).await; + assert_eq!(rows.len(), 2, "deleted full row must stay deleted"); + for row in rows { + let m: serde_json::Value = serde_json::from_str(row.metadata.as_deref().unwrap()).unwrap(); + assert_eq!(m["proxy"]["pair_id"], original); + assert_eq!(m["keep"], "original"); + if row.turn_id == "b" { + assert_eq!(m["new-key"], "fresh value"); + assert!(row.version > before_b); + } + } + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_deleted") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +// @scenario CLICKHOUSE-PAIR-REPAIR-001 integration +#[tokio::test] +async fn pairing_retention_uses_end_time_and_does_not_resurrect_pending_members() { + use std::sync::atomic::Ordering; + use std::time::{Duration, SystemTime}; + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_retention").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.write_rows = 1; + backend + .write_traces(vec![ + synthetic_trace("a-keep", "same", 100, 1000, 1), + synthetic_trace("b-expire", "same", 200, 400, 2), + ]) + .await + .unwrap(); + backend + .pairing_faults + .after_trace_chunks + .store(1, Ordering::SeqCst); + assert!(backend.sweep_pair_window(0, 2000).await.is_err()); + let mut policy = h_storage::retention::RetentionPolicy::default(); + policy.traces_before = Some(SystemTime::UNIX_EPOCH + Duration::from_micros(500)); + let report = backend.apply_retention(policy).await.unwrap(); + assert_eq!(report.traces_deleted, 1); + assert_eq!( + crate::it::count(&backend, "trace_pair_candidates FINAL").await, + 1, + "candidate retention matches END, not start" + ); + let restarted = reconnect(&backend); + let stats = restarted.sweep_pair_window(3000, 4000).await.unwrap(); + assert_eq!(stats.pairs_assigned, 1); + assert_eq!(stats.turns_tagged, 0); + assert_eq!(metadata_rows(&backend).await.len(), 1); + assert_eq!( + crate::it::count(&backend, "trace_pair_repairs FINAL").await, + 0 + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_retention") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-PAIR-PAGING-001 integration +// @scenario CLICKHOUSE-PAIR-REPAIR-001 integration +#[tokio::test] +async fn pairing_budget_error_never_publishes_a_truncated_cluster_or_plan() { + for budget_kind in [0, 1, 2] { + let Some(mut backend) = crate::it::fresh_backend("heron_it_pair_budget").await else { + return; + }; + backend.summary_worker.stop(); + backend.pairing_limits.page_rows = 1; + if budget_kind == 1 { + backend.pairing_limits.plan_bytes = 128; + } else if budget_kind == 0 { + backend.pairing_limits.open_members = 2; + } + backend + .write_traces(vec![ + synthetic_trace("a", "same", 100, 1_000_000, 1), + synthetic_trace("b", "same", 90_100, 900_000, 2), + synthetic_trace("c", "same", 180_100, 800_000, 3), + ]) + .await + .unwrap(); + if budget_kind == 2 { + let calls = backend.query_pair_candidates(0, 2_000_000).await.unwrap(); + // The source calls alone fit. The original plan and classifier + // copies must share this same budget, rather than each getting it. + backend.pairing_limits.retained_bytes = calls + .iter() + .map(crate::pairing_groups::candidate_bytes) + .sum::() + + 1; + } + let err = backend.sweep_pair_window(0, 2_000_000).await.unwrap_err(); + assert!(err.to_string().contains("aggregation budget exceeded")); + assert_eq!( + crate::it::count(&backend, "trace_pair_repairs FINAL").await, + 0 + ); + for row in metadata_rows(&backend).await { + let m: serde_json::Value = + serde_json::from_str(row.metadata.as_deref().unwrap()).unwrap(); + assert!(m.get("proxy").is_none()); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_budget") + .execute() + .await + .unwrap(); + } +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_initial_index_covers_pre_view_future_rows_without_forward_rebackfill() { + let Some(backend) = crate::it::fresh_backend("heron_it_pair_future_coverage").await else { + return; + }; + backend.summary_worker.stop(); + backend + .exec("DROP TABLE trace_pair_candidates_mv") + .await + .unwrap(); + backend + .write_traces(vec![ + synthetic_trace("future-a", "same", 600, 1000, 1), + synthetic_trace("future-b", "same", 610, 990, 2), + // The maximum observed timestamp must be included despite exclusive hi. + synthetic_trace("future-max", "different", 1000, 1100, 3), + ]) + .await + .unwrap(); + let initial = backend.query_pair_candidates(0, 500).await.unwrap(); + let initialized_revision = state_revision(&backend).await; + let restarted = reconnect(&backend); + let ids: Vec<_> = restarted + .query_pair_candidates(0, 1001) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + let forward_revision = state_revision(&restarted).await; + // New future inserts beyond that initial source highwater are covered by MV. + backend + .write_traces(vec![synthetic_trace("post-view", "new", 2000, 2100, 4)]) + .await + .unwrap(); + let later = reconnect(&backend); + let later_ids: Vec<_> = later + .query_pair_candidates(0, 2001) + .await + .unwrap() + .into_iter() + .map(|c| c.turn_id) + .collect(); + let final_revision = state_revision(&later).await; + let paired = later.sweep_pair_window(0, 2001).await.unwrap(); + // Clean up before the expected RED assertion, including the source rows. + backend + .admin_client() + .query("DROP DATABASE heron_it_pair_future_coverage") + .execute() + .await + .unwrap(); + assert!(initial.is_empty()); + assert_eq!(ids, ["future-a", "future-b", "future-max"]); + assert_eq!( + later_ids, + ["future-a", "future-b", "future-max", "post-view"] + ); + assert_eq!((paired.pairs_assigned, paired.turns_tagged), (1, 2)); + assert_eq!( + forward_revision, initialized_revision, + "advancing hi must reuse the completed source snapshot, not rebackfill history" + ); + assert_eq!( + final_revision, initialized_revision, + "normal forward windows and restart must not rerun authoritative initialization" + ); +} diff --git a/server/h-storage-clickhouse/src/retention.rs b/server/h-storage-clickhouse/src/retention.rs index c9e47982..455730f0 100644 --- a/server/h-storage-clickhouse/src/retention.rs +++ b/server/h-storage-clickhouse/src/retention.rs @@ -68,6 +68,7 @@ impl ClickHouseBackend { } pub(crate) async fn apply_retention(&self, policy: RetentionPolicy) -> Result { + let _pairing_gate = self.pairing_gate.lock().await; let mut report = RetentionReport::default(); // Tables touched this sweep — used to drive the optional OPTIMIZE FINAL. let mut swept: Vec<&'static str> = Vec::new(); @@ -96,10 +97,14 @@ impl ClickHouseBackend { if let Some(cutoff) = policy.traces_before { let us = cutoff_micros(cutoff)?; let predicate = format!("end_time < fromUnixTimestamp64Micro({us})"); + // Auxiliary deletion must finish before authoritative deletion. + // Failed/partial repair always re-reads traces, skipping missing IDs. + self.exec(&format!("ALTER TABLE trace_pair_candidates DELETE WHERE {predicate} SETTINGS mutations_sync=1")).await?; report.traces_deleted = self.count_where("traces", &predicate).await?; self.exec(&format!("DELETE FROM traces WHERE {predicate}")) .await?; swept.push("traces"); + swept.push("trace_pair_candidates"); } // Per-granularity metrics sweep. For each (label, cutoff) pair, delete @@ -111,8 +116,9 @@ impl ClickHouseBackend { for (label, cutoff) in &policy.metrics_before { let us = cutoff_micros(*cutoff)?; let label_lit = label.replace('\'', "''"); - let predicate = - format!("granularity = '{label_lit}' AND timestamp < fromUnixTimestamp64Micro({us})"); + let predicate = format!( + "granularity = '{label_lit}' AND timestamp < fromUnixTimestamp64Micro({us})" + ); let n = self.count_where("llm_metrics", &predicate).await?; self.exec(&format!("DELETE FROM llm_metrics WHERE {predicate}")) diff --git a/server/h-storage-clickhouse/src/retention_tests.rs b/server/h-storage-clickhouse/src/retention_tests.rs index 8efdc9e7..600f0927 100644 --- a/server/h-storage-clickhouse/src/retention_tests.rs +++ b/server/h-storage-clickhouse/src/retention_tests.rs @@ -170,3 +170,52 @@ async fn count_failure_propagates_as_error() { "count failure must not become a zero-row report" ); } + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_candidate_retention_failure_stops_before_authoritative_delete() { + let mock = Mock::start(); + mock.fail_on("ALTER TABLE trace_pair_candidates DELETE"); + let policy = RetentionPolicy { + traces_before: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)), + ..Default::default() + }; + assert!(test_backend(&mock, false) + .apply_retention(policy) + .await + .is_err()); + let statements = mock.sql(); + assert!(statements + .contains("end_time < fromUnixTimestamp64Micro(1000000) SETTINGS mutations_sync=1")); + assert!(!statements.contains("DELETE FROM traces")); + assert!(!statements.contains("SELECT count() FROM traces")); +} + +// @scenario CLICKHOUSE-PAIR-INDEX-001 integration +#[tokio::test] +async fn pairing_candidate_cleanup_precedes_traces_and_optional_optimize() { + let mock = Mock::start(); + mock.set_count("traces", 2); + let policy = RetentionPolicy { + traces_before: Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1)), + ..Default::default() + }; + let report = test_backend(&mock, true) + .apply_retention(policy) + .await + .unwrap(); + assert_eq!( + report.total(), + 2, + "auxiliary rows must not change public counts" + ); + let statements = mock.sql(); + assert!( + statements + .find("ALTER TABLE trace_pair_candidates DELETE") + .unwrap() + < statements.find("DELETE FROM traces").unwrap() + ); + assert!(statements.contains("OPTIMIZE TABLE trace_pair_candidates FINAL")); + assert!(statements.contains("OPTIMIZE TABLE traces FINAL")); +} diff --git a/server/h-storage-clickhouse/src/rows.rs b/server/h-storage-clickhouse/src/rows.rs index f104684b..b47d856c 100644 --- a/server/h-storage-clickhouse/src/rows.rs +++ b/server/h-storage-clickhouse/src/rows.rs @@ -16,7 +16,7 @@ use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_protocol::HttpExchange; use h_turn::Trace; -use h_storage::convert::headers_to_json; +use h_storage::convert::{derive_tokens_estimated, headers_to_json}; #[derive(Row, Serialize, Deserialize)] pub(crate) struct CallRow { @@ -61,10 +61,14 @@ pub(crate) struct CallRow { /// column is forward-looking for wire-visible tool spans. Tail field to /// match the `spans` table column order (and the DuckDB layout). pub kind: String, + /// NULL marks a pre-summary legacy write; current writers always send Some. + pub tokens_estimated: Option, } impl From for CallRow { fn from(c: LlmCall) -> Self { + let tokens_estimated = + derive_tokens_estimated(c.input_tokens, c.output_tokens, c.response_body.as_deref()); CallRow { id: c.id, source_id: c.source_id, @@ -106,6 +110,7 @@ impl From for CallRow { process_comm: c.process.as_ref().map(|p| p.comm.clone()), process_exe: c.process.as_ref().and_then(|p| p.exe.clone()), kind: "llm".into(), + tokens_estimated: Some(tokens_estimated), } } } diff --git a/server/h-storage-clickhouse/src/schema.rs b/server/h-storage-clickhouse/src/schema.rs index 171ad0f4..b8476489 100644 --- a/server/h-storage-clickhouse/src/schema.rs +++ b/server/h-storage-clickhouse/src/schema.rs @@ -67,7 +67,8 @@ CREATE TABLE IF NOT EXISTS spans ( process_pid Nullable(UInt32), process_comm Nullable(String), process_exe Nullable(String), - kind String DEFAULT 'llm' + kind String DEFAULT 'llm', + tokens_estimated Nullable(Bool) DEFAULT NULL ) ENGINE = MergeTree ORDER BY (request_time, id) "; @@ -257,6 +258,12 @@ pub(crate) async fn init(backend: &ClickHouseBackend) -> Result<()> { backend.exec(ddl).await?; } + // NULL is intentional: old/legacy writers need the exact Rust helper, not + // a divergent SQL JSON heuristic. The paced worker fills remaining NULLs. + backend.exec("ALTER TABLE spans ADD COLUMN IF NOT EXISTS tokens_estimated Nullable(Bool) DEFAULT NULL").await?; + + crate::pairing::create_schema(backend).await?; + info!(database = %backend.database, "clickhouse storage tables initialized"); Ok(()) } diff --git a/server/h-storage-clickhouse/src/services.rs b/server/h-storage-clickhouse/src/services.rs index d232797b..ac3c10f4 100644 --- a/server/h-storage-clickhouse/src/services.rs +++ b/server/h-storage-clickhouse/src/services.rs @@ -24,18 +24,18 @@ //! a no-JOIN two-step: read the turns + first call_id, fetch those calls, //! then map back in Rust. See `query_services_topology`. -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use clickhouse::Row; use serde::Deserialize; use h_common::error::{AppError, Result}; use h_storage::classify::{classify_app, extract_server_header}; -use h_storage::convert::parse_json_string_list; use h_storage::query::*; use crate::client::ch_err; use crate::sql::time_where; +use crate::topology::{string_bytes, strings_bytes, TopologyBudget}; use crate::ClickHouseBackend; /// Valid `sort_by` fields for `query_services` — mirrors the DuckDB whitelist @@ -60,13 +60,13 @@ const VALID_SORT_FIELDS: &[&str] = &[ /// helper struct: distinct request paths / finish reasons over the clipped /// window plus one small header / body blob per field for the classifier. #[derive(Default)] -struct AppSample { - request_paths: Vec, - finish_reasons: Vec, - sample_response_headers: Option, - sample_request_headers: Option, - sample_request_body: Option, - sample_response_body: Option, +pub(crate) struct AppSample { + pub(crate) request_paths: Vec, + pub(crate) finish_reasons: Vec, + pub(crate) sample_response_headers: Option, + pub(crate) sample_request_headers: Option, + pub(crate) sample_request_body: Option, + pub(crate) sample_response_body: Option, } /// Row of the cheap dim-sample aggregation (distinct paths / finish reasons per @@ -90,6 +90,7 @@ struct BodySampleRow { request_headers: Option, request_body: Option, response_body: Option, + sample_bytes: u64, } /// Main per-endpoint aggregation row for `query_services`. @@ -113,38 +114,6 @@ struct ServiceAggRow { last_seen_ms: i64, } -/// Per-endpoint node aggregation row for `query_services_topology` — same -/// grouping as `query_services`, just the columns the graph needs. -#[derive(Row, Deserialize)] -struct NodeAggRow { - server_ip: String, - server_port: u16, - models: Vec, - request_paths: Vec, - call_count: u64, -} - -/// One turn's proxy metadata + its first call_id, read from `traces`. -/// `span_ids` is the raw JSON-array String column; `first_call_id` is the first -/// element, extracted server-side (`JSONExtractArrayRaw` + `arrayElement`) but -/// re-cleaned in Rust to strip the JSON quoting. -#[derive(Row, Deserialize)] -struct TurnEndpointRow { - proxy_role: String, - pair_id: String, - span_ids: String, -} - -/// `(server_ip, server_port, client_ip)` for one llm_call, used to resolve a -/// turn's endpoint via its first call_id (no-JOIN two-step). -#[derive(Row, Deserialize)] -struct CallEndpointRow { - id: String, - server_ip: String, - server_port: u16, - client_ip: String, -} - impl ClickHouseBackend { /// "Services" view — aggregate `spans` by `(server_ip, server_port)`. /// Port of the DuckDB `query_services`; see that fn + `StorageBackend:: @@ -165,7 +134,11 @@ impl ClickHouseBackend { // Body / header sampling for app classification — separate, clipped // query (keeps the heavy body columns out of the main aggregation). let samples = self - .fetch_app_samples(query.time_range.start_us, query.time_range.end_us) + .fetch_app_samples( + query.time_range.start_us, + query.time_range.end_us, + &mut TopologyBudget::unlimited(), + ) .await?; let where_sql = time_where( @@ -277,15 +250,19 @@ impl ClickHouseBackend { /// outer reads bodies via `id IN (...)`. (The earlier `ROW_NUMBER` /// window read every row's bodies before filtering — ~60× slower.) /// - /// The shape filter (body length + leading `{`, headers leading `[`) runs in - /// Rust on the few returned rows, exactly like the DuckDB version. - async fn fetch_app_samples( + /// SQL applies the same body length / leading-character shape filters before + /// transfer. Streamed sample retention shares the topology aggregation budget. + pub(crate) async fn fetch_app_samples( &self, window_start_us: i64, window_end_us: i64, + budget: &mut TopologyBudget, ) -> Result> { const SAMPLE_WINDOW_US: i64 = 24 * 60 * 60 * 1_000_000; - let sample_start_us = std::cmp::max(window_start_us, window_end_us - SAMPLE_WINDOW_US); + let sample_start_us = std::cmp::max( + window_start_us, + window_end_us.saturating_sub(SAMPLE_WINDOW_US), + ); let sample_where = time_where("request_time", sample_start_us, window_end_us); let mut out: HashMap<(String, u16), AppSample> = HashMap::new(); @@ -300,15 +277,24 @@ impl ClickHouseBackend { groupUniqArray(32)(finish_reason) AS finish_reasons FROM spans WHERE {sample_where} - GROUP BY server_ip, server_port" + GROUP BY server_ip, server_port SETTINGS max_threads=1,max_memory_usage=268435456,group_by_overflow_mode='throw'" ); - let dim_rows = self + let mut dim_rows = self .client .query(&dim_sql) - .fetch_all::() - .await + .fetch::() .map_err(|e| ch_err("fetch_app_samples dim", e))?; - for r in dim_rows { + while let Some(r) = dim_rows + .next() + .await + .map_err(|e| ch_err("fetch_app_samples dim", e))? + { + budget.reserve( + 512 + string_bytes(&r.server_ip) + + strings_bytes(&r.request_paths) + + strings_bytes(&r.finish_reasons), + 1, + )?; out.insert( (r.server_ip, r.server_port), AppSample { @@ -327,39 +313,57 @@ impl ClickHouseBackend { // bodies before filtering — the window read the full ~2 KB body columns // across the whole window (5 s at 1M rows / 37 s at 5M); the two-phase // form is ~60× faster. It's an uncorrelated IN-subquery, not a JOIN, so - // it honours the no-JOIN read rule. Shape filtering happens in Rust below. + // it honours the no-JOIN read rule. SQL prefilters oversized or invalid + // samples; Rust retains the original per-field first-match behavior. + let response_headers="if(startsWith(s.response_headers,'['),toNullable(s.response_headers),CAST(NULL AS Nullable(String)))"; + let request_headers="if(startsWith(s.request_headers,'['),toNullable(s.request_headers),CAST(NULL AS Nullable(String)))"; + let request_body="if(length(ifNull(s.request_body,'')) BETWEEN 100 AND 32768 AND startsWith(ifNull(s.request_body,''),'{'),s.request_body,CAST(NULL AS Nullable(String)))"; + let response_body="if(length(ifNull(s.response_body,'')) BETWEEN 30 AND 8192 AND startsWith(ifNull(s.response_body,''),'{'),s.response_body,CAST(NULL AS Nullable(String)))"; + let sample_bytes=format!("length(ifNull({response_headers},''))+length(ifNull({request_headers},''))+length(ifNull({request_body},''))+length(ifNull({response_body},''))"); + let limit = budget.sample_limit(); let body_sql = format!( "SELECT server_ip, server_port, - toNullable(response_headers) AS response_headers, - toNullable(request_headers) AS request_headers, - request_body, response_body - FROM spans + if(({sample_bytes}) <= {limit},{response_headers},CAST(NULL AS Nullable(String))) AS response_headers, + if(({sample_bytes}) <= {limit},{request_headers},CAST(NULL AS Nullable(String))) AS request_headers, + {request_body} AS request_body, {response_body} AS response_body, + toUInt64({sample_bytes}) AS sample_bytes + FROM spans AS s WHERE id IN ( SELECT id FROM spans WHERE {sample_where} - ORDER BY request_time DESC + ORDER BY request_time DESC,id ASC LIMIT 5 BY server_ip, server_port - )" + ) SETTINGS max_threads=1,max_memory_usage=268435456,read_overflow_mode='throw'" ); - let body_rows = self + let mut body_rows = self .client .query(&body_sql) - .fetch_all::() - .await + .fetch::() .map_err(|e| ch_err("fetch_app_samples body", e))?; // The rows are the (up to) 5 most-recent calls per endpoint; order among // them is unspecified. First-match-wins per field — the filter logic is // order-independent (any shape-valid recent sample classifies the app). - for r in body_rows { + while let Some(r) = body_rows + .next() + .await + .map_err(|e| ch_err("fetch_app_samples body", e))? + { + let bytes = usize::try_from(r.sample_bytes).unwrap_or(usize::MAX); + budget.temporary(bytes.saturating_mul(4).saturating_add(512))?; + if !out.contains_key(&(r.server_ip.clone(), r.server_port)) { + budget.reserve(512 + string_bytes(&r.server_ip), 1)?; + } let entry = out.entry((r.server_ip, r.server_port)).or_default(); if entry.sample_response_headers.is_none() { if let Some(s) = r.response_headers.filter(|s| s.starts_with('[')) { + budget.reserve(string_bytes(&s), 0)?; entry.sample_response_headers = Some(s); } } if entry.sample_request_headers.is_none() { if let Some(s) = r.request_headers.filter(|s| s.starts_with('[')) { + budget.reserve(string_bytes(&s), 0)?; entry.sample_request_headers = Some(s); } } @@ -368,6 +372,7 @@ impl ClickHouseBackend { .request_body .filter(|s| (100..=32768).contains(&s.len()) && s.starts_with('{')) { + budget.reserve(string_bytes(&s), 0)?; entry.sample_request_body = Some(s); } } @@ -376,6 +381,7 @@ impl ClickHouseBackend { .response_body .filter(|s| (30..=8192).contains(&s.len()) && s.starts_with('{')) { + budget.reserve(string_bytes(&s), 0)?; entry.sample_response_body = Some(s); } } @@ -383,350 +389,4 @@ impl ClickHouseBackend { Ok(out) } - - /// Build the service-topology graph for the Path view. Port of the DuckDB - /// `query_services_topology` — same node set, proxy / inferred / client - /// edges, and `__clients__` super-node. The DuckDB original resolves a - /// turn's `(server_ip, server_port)` via a JOIN from `traces` to - /// `spans` on the turn's first `span_ids` entry; the project's no-JOIN - /// rule means we instead read the turns + their first call_id, fetch those - /// calls in one `IN (...)` lookup, and map back in Rust (see below). - pub(crate) async fn query_services_topology( - &self, - query: &ServicesTopologyQuery, - ) -> Result { - let start_us = query.time_range.start_us; - let end_us = query.time_range.end_us; - - // Body / header sampling for app classification — same helper as the - // table view. - let samples = self.fetch_app_samples(start_us, end_us).await?; - - // --- Nodes: one per (server_ip, server_port). Reuses the call_count - // aggregation, just the columns the graph needs. - let nodes_where = time_where("request_time", start_us, end_us); - let nodes_sql = format!( - "SELECT - server_ip, - server_port, - groupUniqArray(32)(model) AS models, - groupUniqArray(16)(request_path) AS request_paths, - count() AS call_count - FROM spans - WHERE {nodes_where} - GROUP BY server_ip, server_port" - ); - let node_rows = self - .client - .query(&nodes_sql) - .fetch_all::() - .await - .map_err(|e| ch_err("query_services_topology nodes", e))?; - - let mut nodes: Vec = Vec::with_capacity(node_rows.len()); - for r in node_rows { - let models = r.models; - let mut request_paths = r.request_paths; - let sample = samples.get(&(r.server_ip.clone(), r.server_port)); - let finish_reasons = sample.map(|s| s.finish_reasons.clone()).unwrap_or_default(); - if let Some(s) = sample { - if !s.request_paths.is_empty() { - request_paths = s.request_paths.clone(); - } - } - let sample_response_headers = sample.and_then(|s| s.sample_response_headers.as_deref()); - let sample_request_headers = sample.and_then(|s| s.sample_request_headers.as_deref()); - let sample_request_body = sample.and_then(|s| s.sample_request_body.as_deref()); - let sample_response_body = sample.and_then(|s| s.sample_response_body.as_deref()); - let server_header = extract_server_header(sample_response_headers); - let app = classify_app( - server_header.as_deref(), - sample_response_headers, - sample_request_headers, - &request_paths, - &finish_reasons, - &models, - sample_request_body, - sample_response_body, - ); - nodes.push(TopologyNode { - server_ip: r.server_ip, - server_port: r.server_port, - app, - models, - call_count: r.call_count, - }); - } - - // --- Resolve each turn's endpoint via its first call_id. The DuckDB - // query JOINs traces → spans on the first span_ids entry; the - // no-JOIN rule means we do this as a two-step: - // 1. read every turn in the window with its proxy role / pair_id and - // its first call_id (parsed from the span_ids JSON in Rust), - // 2. fetch those calls in one IN (...) lookup, build an - // id → (server_ip, server_port, client_ip) map, - // 3. join the two in Rust. - // DIVERGENCE FROM DUCKDB: the original used an in-SQL JOIN / - // correlated extract; we materialize the first span_ids set and do a - // point-lookup batch instead. The resulting (turn, endpoint) pairs are - // identical. - // - // traces is ReplacingMergeTree → FINAL so the latest row wins. - // Time filter on start_time matches the DuckDB predicate. We pull the - // first call id server-side via arrayElement(JSONExtract(span_ids, - // 'Array(String)'), 1); parsing in Rust as a fallback for robustness. - let turns_where = time_where("start_time", start_us, end_us); - let turns_sql = format!( - "SELECT - JSONExtractString(coalesce(metadata, ''), 'proxy', 'role') AS proxy_role, - JSONExtractString(coalesce(metadata, ''), 'proxy', 'pair_id') AS pair_id, - span_ids AS span_ids - FROM traces FINAL - WHERE {turns_where}" - ); - let turn_rows = self - .client - .query(&turns_sql) - .fetch_all::() - .await - .map_err(|e| ch_err("query_services_topology turns", e))?; - - // Per-turn first call_id + role/pair_id. Skip turns with no calls. - struct TurnInfo { - proxy_role: String, - pair_id: String, - first_call_id: String, - } - let mut turn_infos: Vec = Vec::with_capacity(turn_rows.len()); - let mut wanted_ids: HashSet = HashSet::new(); - for t in turn_rows { - let ids = parse_json_string_list(Some(&t.span_ids)); - if let Some(first) = ids.into_iter().next() { - if first.is_empty() { - continue; - } - wanted_ids.insert(first.clone()); - turn_infos.push(TurnInfo { - proxy_role: t.proxy_role, - pair_id: t.pair_id, - first_call_id: first, - }); - } - } - - // Fetch the endpoints for those first span_ids in one batch. - let mut endpoint_by_id: HashMap = HashMap::new(); - if !wanted_ids.is_empty() { - let id_list: Vec = wanted_ids.into_iter().collect(); - let in_list = crate::sql::sql_in_list(&id_list); - let calls_sql = format!( - "SELECT id, server_ip, server_port, client_ip \ - FROM spans WHERE id IN ({in_list})" - ); - let call_rows = self - .client - .query(&calls_sql) - .fetch_all::() - .await - .map_err(|e| ch_err("query_services_topology call endpoints", e))?; - for c in call_rows { - endpoint_by_id.insert(c.id, (c.server_ip, c.server_port, c.client_ip)); - } - } - - // --- Proxy edges: pair each proxy_in turn's endpoint with the - // proxy_out sibling's, grouped by pair_id. Mirrors the DuckDB - // turn_endpoint self-join: a→b where a.pair_id == b.pair_id, - // a.turn != b.turn, a.role == proxy_in, b.role == proxy_out, - // pair_id non-empty, and from != to (drop dup-capture self-pairs). - // Counted by number of (a,b) turn pairs, then aggregated by endpoint - // quad — matching DuckDB's COUNT(*) GROUP BY both endpoints. - let mut by_pair_in: HashMap<&str, Vec<(String, u16)>> = HashMap::new(); - let mut by_pair_out: HashMap<&str, Vec<(String, u16)>> = HashMap::new(); - for ti in &turn_infos { - if ti.pair_id.is_empty() { - continue; - } - let ep = match endpoint_by_id.get(&ti.first_call_id) { - Some((ip, port, _client)) => (ip.clone(), *port), - None => continue, - }; - if ti.proxy_role == "proxy_in" { - by_pair_in.entry(ti.pair_id.as_str()).or_default().push(ep); - } else if ti.proxy_role == "proxy_out" { - by_pair_out.entry(ti.pair_id.as_str()).or_default().push(ep); - } - } - // Aggregate (from_ip, from_port, to_ip, to_port) → turn_count, the - // self-join COUNT(*): for each pair_id, every proxy_in × every - // proxy_out is one pairing. - let mut proxy_counts: HashMap<(String, u16, String, u16), u64> = HashMap::new(); - for (pair_id, ins) in &by_pair_in { - if let Some(outs) = by_pair_out.get(pair_id) { - for (fi, fp) in ins { - for (ti, tp) in outs { - // Drop same-endpoint pairs (multi-interface dup capture, - // not a real proxy hop). - if fi == ti && fp == tp { - continue; - } - *proxy_counts - .entry((fi.clone(), *fp, ti.clone(), *tp)) - .or_insert(0) += 1; - } - } - } - } - let proxy_edges: Vec = proxy_counts - .into_iter() - .map(|((fi, fp, ti, tp), c)| TopologyEdge { - from_ip: fi, - from_port: fp, - to_ip: ti, - to_port: tp, - turn_count: c, - kind: "proxy".to_string(), - }) - .collect(); - - // --- Inbound entry edges, grouped by (caller_ip, to_ip, to_port). - // DuckDB excludes proxy_out turns (their inbound side is the proxy hop, - // already covered above). Resolve each caller_ip to an originating - // service (litellm > proxy-ish > most-active), else fall through to a - // synthetic __clients__ edge. Same logic as the DuckDB resolve_caller. - let mut entry_counts: HashMap<(String, String, u16), u64> = HashMap::new(); - for ti in &turn_infos { - if ti.proxy_role == "proxy_out" { - continue; - } - if let Some((to_ip, to_port, caller_ip)) = endpoint_by_id.get(&ti.first_call_id) { - *entry_counts - .entry((caller_ip.clone(), to_ip.clone(), *to_port)) - .or_insert(0) += 1; - } - } - - // Per-IP service index for caller resolution. - let mut services_by_ip: HashMap<&str, Vec<&TopologyNode>> = HashMap::new(); - for n in &nodes { - services_by_ip - .entry(n.server_ip.as_str()) - .or_default() - .push(n); - } - let app_of: HashMap<(String, u16), Option> = nodes - .iter() - .map(|n| ((n.server_ip.clone(), n.server_port), n.app.clone())) - .collect(); - let is_proxy_app = |app: Option<&str>| { - matches!(app, Some("litellm") | Some("haproxy") | Some("nginx")) - }; - let resolve_caller = |caller_ip: &str, to_ip: &str, to_port: u16| -> Option<(String, u16)> { - // If the TARGET is itself a proxy, inbound calls are real clients, - // not another local service forwarding. - let target_app = app_of - .get(&(to_ip.to_string(), to_port)) - .and_then(|a| a.as_deref()); - if is_proxy_app(target_app) { - return None; - } - let candidates = services_by_ip.get(caller_ip)?; - let usable: Vec<&&TopologyNode> = candidates - .iter() - .filter(|n| !(n.server_ip == to_ip && n.server_port == to_port)) - .collect(); - if usable.is_empty() { - return None; - } - // 1) Prefer litellm. - if let Some(n) = usable.iter().find(|n| n.app.as_deref() == Some("litellm")) { - return Some((n.server_ip.clone(), n.server_port)); - } - // 2) Else any proxy-ish app. - if let Some(n) = usable.iter().find(|n| is_proxy_app(n.app.as_deref())) { - return Some((n.server_ip.clone(), n.server_port)); - } - // 3) Else most-active service on that IP. - let n = usable - .iter() - .max_by_key(|n| n.call_count) - .expect("usable non-empty"); - Some((n.server_ip.clone(), n.server_port)) - }; - - // Dedupe inferred edges against proxy_pair edges already produced. - let proxy_pair_set: HashSet<(String, u16, String, u16)> = proxy_edges - .iter() - .map(|e| (e.from_ip.clone(), e.from_port, e.to_ip.clone(), e.to_port)) - .collect(); - - let mut inferred_dedup: HashMap<(String, u16, String, u16), u64> = HashMap::new(); - let mut client_dedup: HashMap<(String, u16), u64> = HashMap::new(); - for ((caller_ip, to_ip, to_port), turn_count) in entry_counts { - match resolve_caller(&caller_ip, &to_ip, to_port) { - Some((from_ip, from_port)) => { - // Suppress if the pair sweeper already covered this hop. - if proxy_pair_set.contains(&( - from_ip.clone(), - from_port, - to_ip.clone(), - to_port, - )) { - continue; - } - *inferred_dedup - .entry((from_ip, from_port, to_ip, to_port)) - .or_insert(0) += turn_count; - } - None => { - *client_dedup.entry((to_ip, to_port)).or_insert(0) += turn_count; - } - } - } - - let inferred_edges: Vec = inferred_dedup - .into_iter() - .map(|((fi, fp, ti, tp), c)| TopologyEdge { - from_ip: fi, - from_port: fp, - to_ip: ti, - to_port: tp, - turn_count: c, - kind: "inferred".to_string(), - }) - .collect(); - let client_edges: Vec = client_dedup - .into_iter() - .map(|((ti, tp), c)| TopologyEdge { - from_ip: "__clients__".to_string(), - from_port: 0, - to_ip: ti, - to_port: tp, - turn_count: c, - kind: "client".to_string(), - }) - .collect(); - - let mut edges = proxy_edges; - edges.extend(inferred_edges); - edges.extend(client_edges); - - // Synthetic __clients__ node — total = sum of every client edge. - let client_total: u64 = edges - .iter() - .filter(|e| e.kind == "client") - .map(|e| e.turn_count) - .sum(); - if client_total > 0 { - nodes.push(TopologyNode { - server_ip: "__clients__".to_string(), - server_port: 0, - app: Some("clients".to_string()), - models: Vec::new(), - call_count: client_total, - }); - } - - Ok(ServicesTopology { nodes, edges }) - } } diff --git a/server/h-storage-clickhouse/src/summary.rs b/server/h-storage-clickhouse/src/summary.rs new file mode 100644 index 00000000..47319920 --- /dev/null +++ b/server/h-storage-clickhouse/src/summary.rs @@ -0,0 +1,293 @@ +//! Legacy span-summary maintenance. Non-NULL is the durable completion marker. +use std::sync::Mutex; +use std::time::Duration; + +use clickhouse::{Client, Row}; +use serde::Deserialize; +use tokio::task::JoinHandle; + +use h_common::error::Result; +use h_storage::convert::derive_tokens_estimated; + +use crate::client::ch_err; +use crate::sql::escape_str; + +const PAGE_ROWS: usize = 128; +const PAGE_BODY_TARGET: usize = 1024 * 1024; +const QUERY_LIMITS: &str = "max_threads=1, max_memory_usage=268435456"; +// Keep the MergeTree read-in-order path and small blocks. ClickHouse checks +// max_rows_to_read against all planned marks before LIMIT, so using that guard +// here would reject an indexed page merely because later history is large. +const SELECT_LIMITS: &str = "max_threads=1,max_memory_usage=268435456,max_block_size=128,read_overflow_mode='throw',optimize_read_in_order=1"; + +#[derive(Default)] +pub(crate) struct SummaryWorker(Mutex>>); + +impl SummaryWorker { + pub(crate) fn start(&self, client: Client) { + let mut handle = self.0.lock().unwrap(); + if handle.as_ref().is_some_and(|h| !h.is_finished()) { + return; + } + // Own only a client, never the backend / an Arc to it. Drop can abort us. + *handle = Some(tokio::spawn(async move { + let mut state = BackfillState::default(); + loop { + // Pace after completion too: slow queries never cause catch-up bursts. + tokio::time::sleep(Duration::from_secs(1)).await; + if let Err(error) = state.step(&client).await { + tracing::warn!(%error, "clickhouse span summary backfill will retry"); + } + } + })); + } + + #[cfg(test)] + pub(crate) fn stop(&self) -> Option { + self.0.lock().unwrap().take().map(|handle| { + let abort = handle.abort_handle(); + handle.abort(); + abort + }) + } +} + +impl Drop for SummaryWorker { + fn drop(&mut self) { + if let Some(handle) = self.0.get_mut().unwrap().take() { + handle.abort(); + } + } +} + +#[derive(Clone, Debug, Row, Deserialize)] +pub(crate) struct SpanKey { + pub(crate) request_time: i64, + pub(crate) id: String, +} + +impl SpanKey { + pub(crate) fn tuple_sql(&self) -> String { + format!( + "(fromUnixTimestamp64Micro({}), '{}')", + self.request_time, + escape_str(&self.id) + ) + } +} + +#[derive(Row, Deserialize)] +struct LegacyRow { + request_time: i64, + id: String, + input_tokens: Option, + output_tokens: Option, + response_body: Option, +} + +#[derive(Row, Deserialize)] +struct PhysicalRow { + request_time: i64, + id: String, + tokens_estimated: Option, + input_tokens: Option, + output_tokens: Option, +} + +#[derive(Default)] +pub(crate) struct BackfillState { + highwater: Option, + cursor: Option, +} + +impl BackfillState { + #[cfg(test)] + pub(crate) fn after_key(cursor: SpanKey) -> Self { + Self { + cursor: Some(cursor), + highwater: None, + } + } + + /// One physical key page and at most one acknowledged mutation. Known rows + /// do not hydrate bodies. Non-NULL marks completed work durably across + /// restarts; an in-memory cursor bounds each SELECT through known history. + pub(crate) async fn step(&mut self, client: &Client) -> Result { + if self.highwater.is_none() { + let sql = format!("SELECT request_time,id FROM spans ORDER BY request_time DESC,id DESC LIMIT 1 SETTINGS {SELECT_LIMITS}"); + self.highwater = client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("summary highwater", e))? + .next() + .await + .map_err(|e| ch_err("summary highwater", e))?; + } + let Some(highwater) = self.highwater.as_ref() else { + return Ok(0); + }; + let after = self + .cursor + .as_ref() + .map(|key| { + format!( + " AND request_time >= fromUnixTimestamp64Micro({}) AND (request_time,id) > {}", + key.request_time, + key.tuple_sql() + ) + }) + .unwrap_or_default(); + // Do not filter NULL here: sparse unknowns must not turn LIMIT into a + // historical scan. Read an indexed physical page before finding work. + // The scalar bounds are necessary too: ClickHouse does not time-prune + // tuple inequalities alone, especially for a cursor near the tail. + let sql = format!("SELECT request_time,id,tokens_estimated,input_tokens,output_tokens FROM spans WHERE request_time <= fromUnixTimestamp64Micro({}) AND (request_time,id) <= {}{after} ORDER BY request_time ASC,id ASC LIMIT {PAGE_ROWS} SETTINGS {SELECT_LIMITS}",highwater.request_time,highwater.tuple_sql()); + let mut stream = client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("summary keys", e))?; + let mut rows = Vec::with_capacity(PAGE_ROWS); + while let Some(row) = stream.next().await.map_err(|e| ch_err("summary keys", e))? { + rows.push(row); + } + drop(stream); + if rows.is_empty() { + self.highwater = None; + self.cursor = None; + return Ok(0); + } + let unknowns = rows + .iter() + .filter(|r| { + r.tokens_estimated.is_none() + && (r.input_tokens.unwrap_or(0) > 0 || r.output_tokens.unwrap_or(0) > 0) + }) + .map(|r| SpanKey { + request_time: r.request_time, + id: r.id.clone(), + }) + .collect::>(); + let mut summaries = std::collections::HashMap::new(); + let mut stopped_at = None; + if !unknowns.is_empty() { + let first = unknowns.first().unwrap().request_time; + let last = unknowns.last().unwrap().request_time; + let tuples = unknowns + .iter() + .map(SpanKey::tuple_sql) + .collect::>() + .join(","); + let sql=format!("SELECT request_time,id,input_tokens,output_tokens,if(coalesce(input_tokens,0)=0 AND coalesce(output_tokens,0)=0,CAST(NULL AS Nullable(String)),response_body) AS response_body FROM spans WHERE tokens_estimated IS NULL AND request_time >= fromUnixTimestamp64Micro({first}) AND request_time <= fromUnixTimestamp64Micro({last}) AND (request_time,id) IN ({tuples}) ORDER BY request_time ASC,id ASC SETTINGS {SELECT_LIMITS}"); + let mut stream = client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("summary bodies", e))?; + let mut body_bytes = 0usize; + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("summary bodies", e))? + { + body_bytes = + body_bytes.saturating_add(row.response_body.as_ref().map_or(0, String::len)); + let value = derive_tokens_estimated( + row.input_tokens, + row.output_tokens, + row.response_body.as_deref(), + ); + let key = SpanKey { + request_time: row.request_time, + id: row.id, + }; + summaries.insert((key.request_time, key.id.clone()), value); + // One oversized body is necessary for the exact Rust heuristic. + // Release each body now; don't skip any unprocessed key at the cap. + if body_bytes >= PAGE_BODY_TARGET { + stopped_at = Some(key); + break; + } + } + } + let mut values = Vec::new(); + let mut processed = 0; + let mut last_key = None; + for row in rows { + let key = SpanKey { + request_time: row.request_time, + id: row.id, + }; + if stopped_at.as_ref().is_some_and(|last: &SpanKey| { + (key.request_time, key.id.as_str()) > (last.request_time, last.id.as_str()) + }) { + break; + } + if row.tokens_estimated.is_none() { + let value = + if row.input_tokens.unwrap_or(0) == 0 && row.output_tokens.unwrap_or(0) == 0 { + Some(false) + } else { + summaries.remove(&(key.request_time, key.id.clone())) + }; + if let Some(value) = value { + values.push((key.clone(), value)); + } + // A missing hydrated row was deleted or summarized concurrently. + } + processed += 1; + last_key = Some(key); + } + if !values.is_empty() { + let conditions = values + .iter() + .map(|(key, value)| { + format!( + "(request_time,id) = {},toUInt8({})", + key.tuple_sql(), + u8::from(*value) + ) + }) + .collect::>() + .join(","); + let keys = values + .iter() + .map(|(key, _)| key.tuple_sql()) + .collect::>() + .join(","); + let first = values.first().unwrap().0.request_time; + let last = values.last().unwrap().0.request_time; + let sql=format!("ALTER TABLE spans UPDATE tokens_estimated = CAST(multiIf({conditions},toUInt8(0)) AS Nullable(Bool)) WHERE tokens_estimated IS NULL AND request_time >= fromUnixTimestamp64Micro({first}) AND request_time <= fromUnixTimestamp64Micro({last}) AND (request_time,id) IN ({keys}) SETTINGS mutations_sync=1,{QUERY_LIMITS}"); + client + .query(&sql) + .execute() + .await + .map_err(|e| ch_err("summary mutation", e))?; + } + // Advance known-only pages too; failed mutations never reach this line. + self.cursor = last_key; + Ok(processed) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // @scenario CLICKHOUSE-LIST-SUMMARY-001 unit + #[tokio::test] + async fn worker_start_is_idempotent_and_drop_aborts_without_a_backend_cycle() { + let mock = crate::test_mock::Mock::start(); + let backend = crate::test_mock::test_backend(&mock, false); + let worker = SummaryWorker::default(); + worker.start(backend.client.clone()); + let abort = worker.0.lock().unwrap().as_ref().unwrap().abort_handle(); + worker.start(backend.client.clone()); + assert_eq!(worker.0.lock().unwrap().as_ref().unwrap().id(), abort.id()); + drop(worker); + tokio::task::yield_now().await; + assert!(abort.is_finished(), "Drop must abort its client-only task"); + assert!( + mock.statements().is_empty(), + "the worker begins with a paced delay" + ); + } +} diff --git a/server/h-storage-clickhouse/src/summary_tests.rs b/server/h-storage-clickhouse/src/summary_tests.rs new file mode 100644 index 00000000..e83b02f0 --- /dev/null +++ b/server/h-storage-clickhouse/src/summary_tests.rs @@ -0,0 +1,1140 @@ +//! Long-running ClickHouse read regressions; live cases require the real test server. +use crate::it::fixtures::sample_call; +use clickhouse::Row; +use serde::Deserialize; + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn new_span_summaries_match_exact_rust_usage_rules() { + let Some(backend) = crate::it::fresh_backend("heron_it_summary_rules").await else { + return; + }; + let cases = [ + (None, 1, true), + (Some(""), 1, true), + (Some("not json"), 1, true), + (Some(r#"{"usage":{"prompt_tokens":2}}"#), 1, false), + (Some(r#"{"usage":{"completion_tokens":2}}"#), 1, false), + (Some(r#"{"usage":{"input_tokens":2}}"#), 1, false), + (Some(r#"{"usage":{"output_tokens":2}}"#), 1, false), + (Some(r#"{"usage":{"prompt_tokens":0}}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":-2}}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":2.5}}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":"2"}}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":true}}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":{"value":2}}}"#), 1, true), + (Some(r#"{"usage":2}"#), 1, true), + (Some(r#"{"usage":{"prompt_tokens":2}}"#), 0, false), + ]; + let calls = cases + .iter() + .enumerate() + .map(|(i, (body, tokens, _))| { + let mut call = sample_call(&format!("summary-{i:02}"), 1_000_000 + i as i64); + call.client_ip = "192.0.2.1".parse().unwrap(); + call.server_ip = "192.0.2.2".parse().unwrap(); + call.input_tokens = Some(*tokens); + call.output_tokens = Some(0); + call.response_body = body.map(str::to_owned); + call + }) + .collect(); + backend.write_spans(calls).await.unwrap(); + #[derive(Row, Deserialize)] + struct Summary { + id: String, + tokens_estimated: Option, + } + let rows = backend + .client + .query("SELECT id,tokens_estimated FROM spans ORDER BY id") + .fetch_all::() + .await + .expect("new writers persist nullable summary"); + assert_eq!(rows.len(), cases.len()); + for (i, row) in rows.iter().enumerate() { + assert_eq!(row.id, format!("summary-{i:02}")); + assert_eq!(row.tokens_estimated, Some(cases[i].2), "fixture {i}"); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_rules") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 unit +#[tokio::test] +async fn summarized_list_projection_never_requests_response_body() { + use h_storage::query::{DimensionFilter, SpansQuery, TimeRange}; + let mock = crate::test_mock::Mock::start(); + let backend = crate::test_mock::test_backend(&mock, false); + let query = SpansQuery { + time_range: TimeRange { + start_us: 1_000_000, + end_us: 2_000_000, + }, + filter: DimensionFilter::default(), + status_codes: vec![], + finish_reasons: vec![], + client_ips: vec![], + server_ports: vec![], + request_path_contains: None, + is_stream: None, + sort_by: "request_time".into(), + sort_order: "asc".into(), + page: 1, + page_size: 10, + }; + let page = backend.query_spans(&query).await.unwrap(); + assert!(page.items.is_empty()); + let statements = mock.statements(); + let items = statements + .iter() + .find(|s| s.contains("ORDER BY request_time")) + .unwrap(); + assert!( + !items.contains("response_body"), + "list transported a body column: {items}" + ); + assert!(items.contains("tokens_estimated")); +} + +// @scenario CLICKHOUSE-TOPOLOGY-BOUNDED-001 integration +#[tokio::test] +async fn topology_preserves_cross_batch_endpoint_multiplicities() { + use crate::it::fixtures::sample_turn; + use h_storage::query::{ServicesTopologyQuery, TimeRange}; + let Some(backend) = crate::it::fresh_backend("heron_it_topology_cross_batch").await else { + return; + }; + let mut traces = Vec::new(); + let mut calls = Vec::new(); + for i in 0..310 { + let id = format!("topology-turn-{i:03}"); + let span_id = format!("topology-span-{i:03}"); + let at = 10_000_000 + i as i64 * 1_000; + let role = match i { + 0 | 1 => Some("proxy_in"), + 300..=302 => Some("proxy_out"), + _ => None, + }; + let ids = if role.is_some() { + vec![span_id.as_str()] + } else { + vec![] + }; + let mut turn = sample_turn(&id, "synthetic-topology-session", at, ids); + turn.client_ip = "192.0.2.10".parse().unwrap(); + turn.server_ip = "192.0.2.20".parse().unwrap(); + if let Some(role) = role { + turn.metadata = serde_json::json!({"proxy":{"role":role,"pair_id":"synthetic-group"}}); + let mut call = sample_call(&span_id, at); + call.client_ip = "192.0.2.10".parse().unwrap(); + call.server_ip = if role == "proxy_in" { + "192.0.2.20" + } else { + "203.0.113.20" + } + .parse() + .unwrap(); + call.server_port = if role == "proxy_in" { 8080 } else { 9090 }; + calls.push(call); + } + traces.push(turn); + } + backend.write_spans(calls).await.unwrap(); + backend.write_traces(traces).await.unwrap(); + let graph = backend + .query_services_topology(&ServicesTopologyQuery { + time_range: TimeRange { + start_us: 9_000_000, + end_us: 20_000_000, + }, + }) + .await + .unwrap(); + let proxy: Vec<_> = graph.edges.iter().filter(|e| e.kind == "proxy").collect(); + assert_eq!(proxy.len(), 1); + assert_eq!( + (proxy[0].from_ip.as_str(), proxy[0].from_port), + ("192.0.2.20", 8080) + ); + assert_eq!( + (proxy[0].to_ip.as_str(), proxy[0].to_port), + ("203.0.113.20", 9090) + ); + assert_eq!( + proxy[0].turn_count, 6, + "two inbound occurrences times three outbound occurrences" + ); + let clients: Vec<_> = graph.edges.iter().filter(|e| e.kind == "client").collect(); + assert_eq!(clients.len(), 1); + assert_eq!(clients[0].turn_count, 2); + assert_eq!( + graph + .nodes + .iter() + .find(|n| n.server_ip == "__clients__") + .unwrap() + .call_count, + 2 + ); + assert_eq!( + graph + .nodes + .iter() + .find(|n| n.server_ip == "192.0.2.20") + .unwrap() + .call_count, + 2 + ); + assert_eq!( + graph + .nodes + .iter() + .find(|n| n.server_ip == "203.0.113.20") + .unwrap() + .call_count, + 3 + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_topology_cross_batch") + .execute() + .await + .unwrap(); +} + +// Missing automatic maintenance leaves these legacy rows NULL indefinitely. +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn legacy_summary_worker_is_paced_and_wraps_for_late_rows() { + use h_storage::StorageBackend; + use std::time::Duration; + let Some(mut backend) = crate::it::fresh_backend("heron_it_summary_worker").await else { + return; + }; + // Start the worker only after preparing legacy rows, so fixture writes and + // the NULL reset cannot race the maintenance task started by fresh_backend. + backend.summary_worker.stop(); + let mut calls = Vec::new(); + for i in 0..260 { + let mut call = sample_call(&format!("legacy-{i:03}"), 10_000_000 + i); + call.client_ip = "192.0.2.1".parse().unwrap(); + call.server_ip = "192.0.2.2".parse().unwrap(); + call.response_body = Some(r#"{"usage":{"input_tokens":2}}"#.into()); + calls.push(call); + } + backend.write_spans(calls).await.unwrap(); + backend.exec("ALTER TABLE spans UPDATE tokens_estimated=CAST(NULL AS Nullable(Bool)) WHERE 1 SETTINGS mutations_sync=1").await.unwrap(); + let query_tag = format!("heron-summary-worker-{}", test_nonce()); + backend.client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("log_comment", query_tag.clone()); + backend.init().await.unwrap(); + wait_for_summary_worker(&backend, "legacy rows were never summarized").await; + + // A legacy writer inserts an older key after the completed pass. Correct + // filling requires the worker's highwater/keyset pass to wrap. + backend.exec("INSERT INTO spans (id,client_ip,client_port,server_ip,server_port,request_time,wire_api,model,api_type,is_stream,request_path,input_tokens,output_tokens,response_body,request_headers,response_headers) VALUES ('late-old','192.0.2.1',1,'192.0.2.2',2,fromUnixTimestamp64Micro(1),'openai-chat','synthetic','chat',false,'/',2,0,'{\"usage\":{\"input_tokens\":2}}','[]','[]')").await.unwrap(); + wait_for_summary_worker(&backend, "late historical insert was skipped by the cursor").await; + + #[derive(Row, Deserialize)] + struct WorkerQuery { + query: String, + started_us: i64, + finished_us: i64, + } + let admin = backend.admin_client(); + let sql=format!("SELECT query,toUnixTimestamp64Micro(query_start_time_microseconds) AS started_us,toUnixTimestamp64Micro(event_time_microseconds) AS finished_us FROM system.query_log WHERE current_database='heron_it_summary_worker' AND log_comment='{query_tag}' AND type='QueryFinish' AND (startsWith(query,'ALTER TABLE spans UPDATE') OR startsWith(query,'SELECT request_time,id,tokens_estimated,input_tokens,output_tokens FROM spans')) ORDER BY query_start_time_microseconds"); + // Visibility of the committed rows can precede the last HTTP acknowledgement. + // Wait for its finished-query event before aborting the worker and checking + // cadence; a slow database has no six-second completion contract. + let queries = tokio::time::timeout(Duration::from_secs(60), async { + loop { + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let queries = admin.query(&sql).fetch_all::().await.unwrap(); + if queries + .iter() + .filter(|r| r.query.starts_with("ALTER TABLE")) + .count() + >= 4 + { + break queries; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + }) + .await + .expect("worker mutation acknowledgements were never recorded"); + backend.summary_worker.stop(); + let mutations: Vec<_> = queries + .iter() + .filter(|r| r.query.starts_with("ALTER TABLE")) + .collect(); + let batch_sizes: Vec<_> = mutations + .iter() + .map(|r| r.query.matches("toUInt8(").count() - 1) + .collect(); + assert_eq!( + batch_sizes, + [128, 128, 4, 1], + "actual mutations must retain the bounded key batches and historical wrap" + ); + for (mutation, (first, last)) in mutations.iter().zip([ + ("legacy-000", "legacy-127"), + ("legacy-128", "legacy-255"), + ("legacy-256", "legacy-259"), + ("late-old", "late-old"), + ]) { + assert!( + mutation.query.contains(&format!("'{first}'")) + && mutation.query.contains(&format!("'{last}'")), + "worker mutated the wrong key range" + ); + } + assert_eq!(crate::it::count(&backend, "spans").await, 261); + for mutation in &mutations[..2] { + let next = queries + .iter() + .find(|r| !r.query.starts_with("ALTER TABLE") && r.started_us > mutation.finished_us) + .expect("next paced key page"); + // Server end/start timestamps avoid inferring cadence from count polls, + // which may observe several real batches at once under scheduler load. + // Allow 50 ms for server logging vs HTTP acknowledgement timestamps. + assert!( + next.started_us - mutation.finished_us >= 950_000, + "worker caught up in a burst after an acknowledged mutation" + ); + eprintln!( + "summary worker acknowledgement-to-next-page: {} us", + next.started_us - mutation.finished_us + ); + } + eprintln!("summary worker acknowledged batch sizes: {batch_sizes:?}"); + admin + .query("DROP DATABASE heron_it_summary_worker") + .execute() + .await + .unwrap(); +} + +async fn wait_for_summary_worker(backend: &crate::ClickHouseBackend, context: &str) { + use std::time::Duration; + let mut remaining = u64::MAX; + // This is an eventual-progress watchdog, not a database latency assertion. + // Reduce polling pressure instead of adding up to 25 queries/second to the + // same resource-limited integration server. + let completed = tokio::time::timeout(Duration::from_secs(60), async { + loop { + remaining = unknown_count(backend).await; + if remaining == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + }) + .await; + assert!( + completed.is_ok(), + "{context}: {remaining} unknown rows remain" + ); +} + +async fn unknown_count(backend: &crate::ClickHouseBackend) -> u64 { + backend + .client + .query("SELECT count() AS n FROM spans WHERE tokens_estimated IS NULL") + .fetch_one::() + .await + .unwrap() + .n +} + +// Full span-ID arrays scale with turn size even when the graph needs one ID. +// @scenario CLICKHOUSE-TOPOLOGY-BOUNDED-001 unit +#[tokio::test] +async fn topology_turn_projection_is_minimal_and_totally_ordered() { + use h_storage::query::{ServicesTopologyQuery, TimeRange}; + let mock = crate::test_mock::Mock::start(); + let backend = crate::test_mock::test_backend(&mock, false); + backend + .query_services_topology(&ServicesTopologyQuery { + time_range: TimeRange { + start_us: 1, + end_us: 2, + }, + }) + .await + .unwrap(); + let statements = mock.statements(); + let turns = statements + .iter() + .find(|s| s.contains("FROM traces FINAL")) + .unwrap(); + assert!( + turns.contains("AS first_call_id"), + "full array projection: {turns}" + ); + assert!(turns.contains("ORDER BY start_time ASC,turn_id ASC")); +} + +// @scenario CLICKHOUSE-TOPOLOGY-BOUNDED-001 integration +#[tokio::test] +async fn topology_first_id_matches_shared_strict_parser() { + use h_storage::convert::parse_json_string_list; + let Some(backend) = crate::it::fresh_backend("heron_it_topology_json").await else { + return; + }; + let cases = [ + "[]", + r#"["first"]"#, + r#"["first","second"]"#, + r#"["","second"]"#, + r#"["first",""#, + "not json", + r#"{"0":"first"}"#, + r#""first""#, + "null", + r#"["first",7]"#, + r#"["first",null]"#, + r#"["first",true]"#, + r#"[7,"second"]"#, + r#"["first",["nested"]]"#, + r#"["first",{"x":1}]"#, + r#"["quote\" and backslash\\ and \u4e2d","tail"]"#, + " \n [ \"first\" , \"second\" ] \t ", + r#"["first",]"#, + r#"["first","\x"]"#, + r#"["first"] extra"#, + "", + " ", + "[\"中😀\",\"tail\"]", + r#"["\ud83d\ude00","tail"]"#, + r#"["first","\ud800"]"#, + r#"["\udc00"]"#, + "[\"first\",\"bad\u{1}\"]", + "\u{feff}[\"first\"]", + " \u{feff}[\"first\"]", + "\u{feff}\u{feff}[\"first\"]", + "[\"\u{feff}first\"]", + ]; + #[derive(Row, Deserialize)] + struct FirstId { + first_call_id: String, + } + for (i, raw) in cases.iter().enumerate() { + let expected = parse_json_string_list(Some(raw)) + .into_iter() + .next() + .unwrap_or_default(); + let sql = format!( + "SELECT {} AS first_call_id FROM (SELECT '{}' AS span_ids)", + crate::topology::first_call_id_sql(), + crate::sql::escape_str(raw) + ); + let actual = backend + .client + .query(&sql) + .fetch_one::() + .await + .unwrap() + .first_call_id; + assert_eq!(actual, expected, "parser fixture {i}"); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_topology_json") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-TOPOLOGY-BOUNDED-001 integration +#[tokio::test] +async fn topology_budget_rejects_samples_and_entries_without_partial_graph() { + use crate::topology::TopologyBudget; + use h_storage::query::{ServicesTopologyQuery, TimeRange}; + let Some(backend) = crate::it::fresh_backend("heron_it_topology_budget").await else { + return; + }; + let mut call = sample_call("budget", 1_000_000); + call.client_ip = "192.0.2.1".parse().unwrap(); + call.server_ip = "192.0.2.2".parse().unwrap(); + backend.write_spans(vec![call]).await.unwrap(); + let query = ServicesTopologyQuery { + time_range: TimeRange { + start_us: 0, + end_us: 2_000_000, + }, + }; + for budget in [ + TopologyBudget::new(128, 100), + TopologyBudget::new(1_000_000, 0), + ] { + let error = backend + .topology_with_budget(&query, budget) + .await + .err() + .expect("budget must fail, never truncate"); + assert!( + error + .to_string() + .contains("topology aggregation budget exceeded"), + "{error}" + ); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_topology_budget") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn backfill_retries_failed_mutation_and_resumes_with_remaining_nulls() { + use crate::summary::BackfillState; + let Some(backend) = crate::it::fresh_backend("heron_it_summary_resume").await else { + return; + }; + backend.summary_worker.stop(); + let calls = (0..260) + .map(|i| { + // Equal-microsecond keys must resume by id without losing siblings. + let mut c = sample_call(&format!("resume-{i:03}"), 10_000_000); + c.client_ip = "192.0.2.1".parse().unwrap(); + c.server_ip = "192.0.2.2".parse().unwrap(); + c.response_body = Some(r#"{"usage":{"prompt_tokens":2}}"#.into()); + c + }) + .collect(); + backend.write_spans(calls).await.unwrap(); + backend.exec("ALTER TABLE spans UPDATE tokens_estimated=CAST(NULL AS Nullable(Bool)) WHERE 1 SETTINGS mutations_sync=1").await.unwrap(); + let mut state = BackfillState::default(); + let readonly = backend.client.clone().with_setting("readonly", "2"); + assert!( + state.step(&readonly).await.is_err(), + "read succeeds then mutation must fail" + ); + assert_eq!(unknown_count(&backend).await, 260); + assert_eq!( + state.step(&backend.client).await.unwrap(), + 128, + "failed page cursor must not advance" + ); + assert_eq!(unknown_count(&backend).await, 132); + // Forget all in-memory cursor state, as a process restart does. + drop(state); + let mut restarted = BackfillState::default(); + assert_eq!(restarted.step(&backend.client).await.unwrap(), 128); + assert_eq!( + unknown_count(&backend).await, + 132, + "restart revisits the completed first key page without rewriting it" + ); + assert_eq!(restarted.step(&backend.client).await.unwrap(), 128); + assert_eq!(unknown_count(&backend).await, 4); + assert_eq!(restarted.step(&backend.client).await.unwrap(), 4); + assert_eq!(unknown_count(&backend).await, 0); + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_resume") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn mixed_list_keeps_legacy_boolean_and_full_bodies() { + use h_storage::query::{DimensionFilter, SpansQuery, TimeRange}; + let Some(mut backend) = crate::it::fresh_backend("heron_it_summary_mixed").await else { + return; + }; + backend.summary_worker.stop(); + let mut calls = Vec::new(); + for (id, tokens, body) in [ + ("known", 1, Some(r#"{"usage":{"input_tokens":2}}"#)), + ("legacy-exact", 1, Some(r#"{"usage":{"input_tokens":2}}"#)), + ("legacy-estimated", 1, Some("invalid")), + ("legacy-zero", 0, Some("invalid")), + ] { + let mut c = sample_call(id, 1_000_001 + calls.len() as i64); + c.client_ip = "192.0.2.1".parse().unwrap(); + c.server_ip = "192.0.2.2".parse().unwrap(); + c.input_tokens = Some(tokens); + c.output_tokens = Some(0); + c.response_body = body.map(str::to_owned); + calls.push(c); + } + backend.write_spans(calls).await.unwrap(); + backend.exec("ALTER TABLE spans UPDATE tokens_estimated=CAST(NULL AS Nullable(Bool)) WHERE id!='known' SETTINGS mutations_sync=1").await.unwrap(); + let mixed_query_id = format!("heron-summary-mixed-{}", test_nonce()); + let base = backend.client.clone(); + backend.client = base + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", mixed_query_id.clone()); + let page = backend + .query_spans(&SpansQuery { + time_range: TimeRange { + start_us: 0, + end_us: 2_000_000, + }, + filter: DimensionFilter::default(), + status_codes: vec![], + finish_reasons: vec![], + client_ips: vec![], + server_ports: vec![], + request_path_contains: None, + is_stream: None, + sort_by: "request_time".into(), + sort_order: "asc".into(), + page: 1, + page_size: 10, + }) + .await + .unwrap(); + backend.client = base; + let admin = backend.admin_client(); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + #[derive(Row, Deserialize)] + struct LegacyLookup { + query: String, + result_rows: u64, + } + let lookups = admin.query(&format!("SELECT query,result_rows FROM system.query_log WHERE current_database='heron_it_summary_mixed' AND type='QueryFinish' AND query_id='{mixed_query_id}' AND startsWith(query,'SELECT request_time,id,tokens_estimated,')")).fetch_all::().await.unwrap(); + assert_eq!(lookups.len(), 1); + let lookup = &lookups[0]; + assert_eq!(lookup.result_rows, 2); + assert!(lookup.query.contains("'legacy-exact'")); + assert!(lookup.query.contains("'legacy-estimated'")); + assert!(!lookup.query.contains("'known'")); + assert!(!lookup.query.contains("'legacy-zero'")); + assert_eq!(page.total, 4); + assert_eq!( + page.items + .iter() + .map(|r| r.tokens_estimated) + .collect::>(), + [false, false, true, false] + ); + assert_eq!( + unknown_count(&backend).await, + 3, + "reads must not launch synchronous migration" + ); + let detail = backend + .query_span_by_id("legacy-exact") + .await + .unwrap() + .unwrap(); + assert_eq!( + detail.response_body.as_deref(), + Some(r#"{"usage":{"input_tokens":2}}"#) + ); + let full = backend + .query_spans_by_ids(&["known".into(), "legacy-estimated".into()], true) + .await + .unwrap(); + assert_eq!(full.len(), 2); + assert!(full.iter().all(|r| r.response_body.is_some())); + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_mixed") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn legacy_schema_init_is_idempotent_and_preserves_body_before_backfill() { + use h_storage::StorageBackend; + let Some(backend) = crate::it::fresh_backend("heron_it_summary_migration").await else { + return; + }; + backend.summary_worker.stop(); + backend + .exec("ALTER TABLE spans DROP COLUMN tokens_estimated") + .await + .unwrap(); + backend.exec("INSERT INTO spans (id,request_time,client_ip,client_port,server_ip,server_port,wire_api,model,api_type,is_stream,request_path,input_tokens,output_tokens,response_body,request_headers,response_headers) VALUES ('legacy','1970-01-01 00:00:01','192.0.2.1',1,'192.0.2.2',2,'openai-chat','synthetic','chat',false,'/',1,0,'{\"usage\":{\"input_tokens\":2}}','[]','[]')").await.unwrap(); + backend.init().await.unwrap(); + backend.init().await.unwrap(); + assert_eq!( + unknown_count(&backend).await, + 1, + "DDL must not force a synchronous full backfill" + ); + let detail = backend.query_span_by_id("legacy").await.unwrap().unwrap(); + assert_eq!( + detail.response_body.as_deref(), + Some(r#"{"usage":{"input_tokens":2}}"#) + ); + backend.summary_worker.stop(); + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_migration") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn summarized_list_transfer_is_independent_of_body_length() { + use h_storage::query::{DimensionFilter, SpansQuery, TimeRange}; + let Some(mut backend) = crate::it::fresh_backend("heron_it_summary_transfer").await else { + return; + }; + backend.summary_worker.stop(); + let mut small = sample_call("small", 1_000_001); + small.client_ip = "192.0.2.1".parse().unwrap(); + small.server_ip = "192.0.2.2".parse().unwrap(); + small.response_body = Some(r#"{"usage":{"input_tokens":2}}"#.into()); + let mut large = small.clone(); + large.id = "large".into(); + large.request_time = 1_000_002; + large.response_body = Some(format!( + "{{\"usage\":{{\"input_tokens\":2}},\"padding\":\"{}\"}}", + "x".repeat(1_048_576) + )); + backend.write_spans(vec![small, large]).await.unwrap(); + let base = backend.client.clone(); + let mut pages = Vec::new(); + let transfer_nonce = test_nonce(); + for (query_tag, at) in [ + ("heron-summary-list-small", 1_000_001), + ("heron-summary-list-large", 1_000_002), + ] { + let query_id = format!("{query_tag}-{transfer_nonce}"); + backend.client = base + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", query_id); + let page = backend + .query_spans(&SpansQuery { + time_range: TimeRange { + start_us: at, + end_us: at + 1, + }, + filter: DimensionFilter::default(), + status_codes: vec![], + finish_reasons: vec![], + client_ips: vec![], + server_ports: vec![], + request_path_contains: None, + is_stream: None, + sort_by: "request_time".into(), + sort_order: "asc".into(), + page: 1, + page_size: 1, + }) + .await + .unwrap(); + assert_eq!(page.total, 1); + assert_eq!(page.items.len(), 1); + pages.push(page); + } + backend.client = base; + let mut left = serde_json::to_value(&pages[0].items[0]).unwrap(); + let mut right = serde_json::to_value(&pages[1].items[0]).unwrap(); + left["id"] = serde_json::Value::Null; + right["id"] = serde_json::Value::Null; + assert_eq!( + left, right, + "complete list payload parity apart from equal-size IDs" + ); + let admin = backend.admin_client(); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + #[derive(Row, Deserialize)] + struct Transfer { + query_id: String, + result_bytes: u64, + read_bytes: u64, + read_rows: u64, + } + let transfers=admin.query(&format!("SELECT query_id,result_bytes,read_bytes,read_rows FROM system.query_log WHERE current_database='heron_it_summary_transfer' AND type='QueryFinish' AND query_id IN ('heron-summary-list-small-{transfer_nonce}','heron-summary-list-large-{transfer_nonce}') AND startsWith(query,'SELECT id, source_id,') ORDER BY query_id")).fetch_all::().await.unwrap(); + assert_eq!(transfers.len(), 2, "one recorded list query per body size"); + assert_eq!(transfers[0].result_bytes, transfers[1].result_bytes); + assert_eq!(transfers[0].read_bytes, transfers[1].read_bytes); + assert_eq!(transfers[0].read_rows, transfers[1].read_rows); + eprintln!("summary list transfer: {} result_bytes={} read_bytes={} rows={}; {} result_bytes={} read_bytes={} rows={}",transfers[0].query_id,transfers[0].result_bytes,transfers[0].read_bytes,transfers[0].read_rows,transfers[1].query_id,transfers[1].result_bytes,transfers[1].read_bytes,transfers[1].read_rows); + let detail = backend.query_span_by_id("large").await.unwrap().unwrap(); + assert!(detail.response_body.unwrap().len() > 1_048_576); + admin + .query("DROP DATABASE heron_it_summary_transfer") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn backfill_step_scan_is_bounded_when_summarized_history_grows() { + use crate::summary::BackfillState; + let Some(backend) = crate::it::fresh_backend("heron_it_summary_scan").await else { + return; + }; + backend.summary_worker.stop(); + backend.exec("INSERT INTO spans (id,request_time,input_tokens,output_tokens,response_body,tokens_estimated) SELECT concat('recent-',toString(number)),fromUnixTimestamp64Micro(toInt64(10000000+number)),1,0,'{\"usage\":{\"input_tokens\":2}}',CAST(NULL AS Nullable(Bool)) FROM numbers(100)").await.unwrap(); + let admin = backend.admin_client(); + let mut previous = 0; + let mut samples = Vec::new(); + #[derive(Row, Deserialize)] + struct Scan { + query: String, + read_rows: u64, + read_bytes: u64, + } + for history in [0, 100_000, 500_000] { + if history > previous { + backend.exec(&format!("INSERT INTO spans (id,request_time,input_tokens,output_tokens,response_body,tokens_estimated) SELECT concat('old-',toString(number)),fromUnixTimestamp64Micro(toInt64(number)),1,0,'{{\"usage\":{{\"input_tokens\":2}}}}',false FROM numbers({previous},{})",history-previous)).await.unwrap(); + } + backend.exec("OPTIMIZE TABLE spans FINAL").await.unwrap(); + backend.exec("ALTER TABLE spans UPDATE tokens_estimated=CAST(NULL AS Nullable(Bool)) WHERE startsWith(id,'recent-') SETTINGS mutations_sync=1").await.unwrap(); + let query_id = format!("heron-summary-step-history-{history}-{}", test_nonce()); + let client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", query_id.clone()); + let mut state = BackfillState::default(); + state.step(&client).await.unwrap(); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let rows=admin.query(&format!("SELECT query,read_rows,read_bytes FROM system.query_log WHERE current_database='heron_it_summary_scan' AND type='QueryFinish' AND query_id='{query_id}' AND startsWith(query,'SELECT request_time,id')")).fetch_all::().await.unwrap(); + assert!( + rows.len() >= 2, + "actualworkerhighwaterandpagequeriesmustbelogged" + ); + let reads = rows.iter().map(|r| r.read_rows).sum::(); + let bytes = rows.iter().map(|r| r.read_bytes).sum::(); + let bodies = rows + .iter() + .filter(|r| r.query.contains("response_body")) + .count(); + eprintln!("summary step scan: known_history={history} fixed_unknown=100 read_rows={reads} read_bytes={bytes} body_queries={bodies}"); + samples.push((history, reads, bytes, bodies)); + if history == 500_000 { + // Place the private test cursor after known history, so this step + // exercises real unknown hydration rather than only the first page. + let tail_id = format!("heron-summary-step-tail-{}", test_nonce()); + let client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", tail_id.clone()); + let mut tail = BackfillState::after_key(crate::summary::SpanKey { + request_time: 499_999, + id: "old-499999".into(), + }); + assert_eq!(tail.step(&client).await.unwrap(), 100); + assert_eq!(unknown_count(&backend).await, 0); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let rows=admin.query(&format!("SELECT query,read_rows,read_bytes FROM system.query_log WHERE current_database='heron_it_summary_scan' AND type='QueryFinish' AND query_id='{tail_id}' AND startsWith(query,'SELECT request_time,id')")).fetch_all::().await.unwrap(); + let reads = rows.iter().map(|r| r.read_rows).sum::(); + let bytes = rows.iter().map(|r| r.read_bytes).sum::(); + assert_eq!(rows.len(), 3); + assert_eq!( + rows.iter() + .filter(|r| r.query.contains("response_body")) + .count(), + 1 + ); + assert!( + reads <= 65_536 && bytes <= 4 * 1024 * 1024, + "unknown hydration scanned old history: {reads} rows, {bytes} bytes" + ); + eprintln!("summary step tail: known_history=500000 fixed_unknown=100 read_rows={reads} read_bytes={bytes} body_queries=1"); + let end_id = format!("heron-summary-step-end-{}", test_nonce()); + let client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", end_id.clone()); + assert_eq!( + tail.step(&client).await.unwrap(), + 0, + "completed pass must wrap without refetching bodies" + ); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + let end_rows=admin.query(&format!("SELECT query,read_rows,read_bytes FROM system.query_log WHERE current_database='heron_it_summary_scan' AND type='QueryFinish' AND query_id='{end_id}' AND startsWith(query,'SELECT request_time,id')")).fetch_all::().await.unwrap(); + assert_eq!(end_rows.len(), 1); + assert!(!end_rows[0].query.contains("response_body")); + assert!(end_rows[0].read_rows <= 65_536); + eprintln!( + "summary step end: known_history=500000 read_rows={} read_bytes={} body_queries=0", + end_rows[0].read_rows, end_rows[0].read_bytes + ); + } + previous = history; + } + // MergeTree may read whole index granules. This measured bound covers the + // highwater, a 128-key page and bounded hydration in this fixture; it is not + // a universal server read-row cap for arbitrarily fragmented tables. + for sample in &samples[1..] { + assert!( + sample.1 <= samples[0].1 + 65_536, + "worker SELECTs scale with historical rows: {samples:?}" + ); + assert!( + sample.2 <= samples[0].2 + 4 * 1024 * 1024, + "worker SELECT bytes scale with historical rows: {samples:?}" + ); + assert_eq!( + sample.3, 0, + "a known-only physical page must not hydrate bodies" + ); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_scan") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-TOPOLOGY-BOUNDED-001 integration +#[tokio::test] +async fn topology_keeps_mirrors_inferred_edges_and_proxy_suppression() { + use crate::it::fixtures::sample_turn; + use h_storage::query::{ServicesTopologyQuery, TimeRange}; + let Some(backend) = crate::it::fresh_backend("heron_it_topology_roles").await else { + return; + }; + let mut spans = Vec::new(); + let mut traces = Vec::new(); + for (i, role, target, port, caller) in [ + (0, "proxy_in", "192.0.2.20", 8080, "192.0.2.10"), + (1, "proxy_in", "192.0.2.20", 8080, "192.0.2.10"), + (2, "proxy_out", "203.0.113.20", 9090, "192.0.2.20"), + (3, "proxy_out", "203.0.113.20", 9090, "192.0.2.20"), + (4, "proxy_out", "203.0.113.20", 9090, "192.0.2.20"), + (5, "mirror_secondary", "192.0.2.20", 8080, "192.0.2.10"), + (6, "", "203.0.113.20", 9090, "192.0.2.20"), + (7, "", "203.0.113.30", 9091, "192.0.2.20"), + ] { + let at = 1_000_001 + i; + let id = format!("role-span-{i}"); + let mut span = sample_call(&id, at); + span.client_ip = caller.parse().unwrap(); + span.server_ip = target.parse().unwrap(); + span.server_port = port; + if target == "192.0.2.20" { + span.response_headers = vec![("x-litellm-call-id".into(), "synthetic".into())]; + } + spans.push(span); + let mut trace = sample_turn( + &format!("role-turn-{i}"), + "synthetic", + at, + vec![id.as_str()], + ); + trace.client_ip = caller.parse().unwrap(); + trace.server_ip = target.parse().unwrap(); + if !role.is_empty() { + trace.metadata = serde_json::json!({"proxy":{"role":role,"pair_id":"synthetic-group"}}); + } + traces.push(trace); + } + backend.write_spans(spans).await.unwrap(); + backend.write_traces(traces).await.unwrap(); + let graph = backend + .query_services_topology(&ServicesTopologyQuery { + time_range: TimeRange { + start_us: 0, + end_us: 2_000_000, + }, + }) + .await + .unwrap(); + let mut edges = graph + .edges + .into_iter() + .map(|e| { + ( + e.kind, + e.from_ip, + e.from_port, + e.to_ip, + e.to_port, + e.turn_count, + ) + }) + .collect::>(); + edges.sort(); + assert_eq!( + edges, + vec![ + ( + "client".into(), + "__clients__".into(), + 0, + "192.0.2.20".into(), + 8080, + 3 + ), + ( + "inferred".into(), + "192.0.2.20".into(), + 8080, + "203.0.113.30".into(), + 9091, + 1 + ), + ( + "proxy".into(), + "192.0.2.20".into(), + 8080, + "203.0.113.20".into(), + 9090, + 6 + ), + ] + ); + assert_eq!( + graph + .nodes + .iter() + .find(|n| n.server_ip == "__clients__") + .unwrap() + .call_count, + 3 + ); + assert_eq!( + graph + .nodes + .iter() + .find(|n| n.server_ip == "192.0.2.20") + .unwrap() + .app + .as_deref(), + Some("litellm") + ); + backend + .admin_client() + .query("DROP DATABASE heron_it_topology_roles") + .execute() + .await + .unwrap(); +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn backfill_body_cap_never_advances_past_unprocessed_unknown_keys() { + use crate::summary::BackfillState; + let Some(backend) = crate::it::fresh_backend("heron_it_summary_body_cap").await else { + return; + }; + backend.summary_worker.stop(); + let mut calls = Vec::new(); + for i in 0..3 { + let mut call = sample_call(&format!("cap-{i}"), 1_000_000 + i); + call.client_ip = "192.0.2.1".parse().unwrap(); + call.server_ip = "192.0.2.2".parse().unwrap(); + call.response_body = Some(format!( + "{{\"usage\":{{\"input_tokens\":2}},\"padding\":\"{}\"}}", + "x".repeat(1_048_576) + )); + calls.push(call); + } + backend.write_spans(calls).await.unwrap(); + backend.exec("ALTER TABLE spans UPDATE tokens_estimated=CAST(NULL AS Nullable(Bool)) WHERE 1 SETTINGS mutations_sync=1").await.unwrap(); + let mut state = BackfillState::default(); + for remaining in [2, 1, 0] { + assert_eq!(state.step(&backend.client).await.unwrap(), 1); + assert_eq!( + unknown_count(&backend).await, + remaining, + "unprocessed oversized keys must survive the cursor" + ); + } + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_body_cap") + .execute() + .await + .unwrap(); +} + +fn test_nonce() -> u128 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() +} + +// @scenario CLICKHOUSE-LIST-SUMMARY-001 integration +#[tokio::test] +async fn backfill_progresses_through_overlapping_unmerged_parts() { + use crate::summary::BackfillState; + let Some(backend) = crate::it::fresh_backend("heron_it_summary_parts").await else { + return; + }; + backend.summary_worker.stop(); + backend.exec("SYSTEM STOP MERGES spans").await.unwrap(); + for part in 0..4 { + backend.exec(&format!("INSERT INTO spans (id,request_time,input_tokens,output_tokens,response_body,tokens_estimated) SELECT concat('part-',toString(number*4+{part})),fromUnixTimestamp64Micro(toInt64(1000000+number*4+{part})),1,0,'{{\"usage\":{{\"input_tokens\":2}}}}',if(number*4+{part}<128,CAST(false AS Nullable(Bool)),CAST(NULL AS Nullable(Bool))) FROM numbers(90)")).await.unwrap(); + } + let parts=backend.client.query("SELECT count() AS n FROM system.parts WHERE active AND database=currentDatabase() AND table='spans'").fetch_one::().await.unwrap().n; + assert_eq!( + parts, 4, + "the read fixture must have four overlapping unmerged parts" + ); + let query_id = format!("heron-summary-parts-{}", test_nonce()); + let client = backend + .client + .clone() + .with_setting("log_queries", "1") + .with_setting("query_id", query_id.clone()); + let mut state = BackfillState::default(); + assert_eq!(state.step(&client).await.unwrap(), 128); + assert_eq!( + unknown_count(&backend).await, + 232, + "completed known first page remains untouched" + ); + let admin = backend.admin_client(); + admin.query("SYSTEM FLUSH LOGS").execute().await.unwrap(); + #[derive(Row, Deserialize)] + struct Statement { + query: String, + read_rows: u64, + read_bytes: u64, + } + let statements=admin.query(&format!("SELECT query,read_rows,read_bytes FROM system.query_log WHERE current_database='heron_it_summary_parts' AND type='QueryFinish' AND query_id='{query_id}'")).fetch_all::().await.unwrap(); + assert_eq!( + statements.len(), + 2, + "known page performs only highwater and physical-key SELECTs" + ); + assert!(statements + .iter() + .all(|s| !s.query.contains("response_body") && !s.query.starts_with("ALTER"))); + eprintln!( + "fragmented summary known page: queries={} read_rows={} read_bytes={}", + statements.len(), + statements.iter().map(|s| s.read_rows).sum::(), + statements.iter().map(|s| s.read_bytes).sum::() + ); + // Mutations require the table's background mutations executor. The pager's + // key read above has already proved the overlapping, unmerged-part path. + backend.exec("SYSTEM START MERGES spans").await.unwrap(); + assert_eq!(state.step(&backend.client).await.unwrap(), 128); + assert_eq!(unknown_count(&backend).await, 104); + assert_eq!(state.step(&backend.client).await.unwrap(), 104); + assert_eq!(unknown_count(&backend).await, 0); + backend + .admin_client() + .query("DROP DATABASE heron_it_summary_parts") + .execute() + .await + .unwrap(); +} diff --git a/server/h-storage-clickhouse/src/test_mock.rs b/server/h-storage-clickhouse/src/test_mock.rs index 0c544d65..b33f75c8 100644 --- a/server/h-storage-clickhouse/src/test_mock.rs +++ b/server/h-storage-clickhouse/src/test_mock.rs @@ -90,6 +90,10 @@ pub(crate) fn test_backend(mock: &Mock, optimize: bool) -> ClickHouseBackend { password: String::new(), database: "heron".to_string(), optimize_on_sweep: optimize, + summary_worker: crate::summary::SummaryWorker::default(), + pairing_gate: tokio::sync::Mutex::new(()), + pairing_limits: crate::pairing::Limits::default(), + pairing_faults: crate::pairing_tests::Faults::default(), } } diff --git a/server/h-storage-clickhouse/src/topology.rs b/server/h-storage-clickhouse/src/topology.rs new file mode 100644 index 00000000..b8b00a3d --- /dev/null +++ b/server/h-storage-clickhouse/src/topology.rs @@ -0,0 +1,473 @@ +//! Bounded topology aggregation; counts retain turn multiplicities across batches. +use std::collections::HashMap; +use std::mem::size_of; + +use clickhouse::Row; +use h_common::error::{AppError, Result}; +use h_storage::classify::{classify_app, extract_server_header}; +use h_storage::query::*; +use serde::Deserialize; + +use crate::client::ch_err; +use crate::sql::{escape_str, time_where}; +use crate::ClickHouseBackend; + +const BATCH_ROWS: usize = 256; +const QUERY_LIMITS: &str = "max_threads=1,max_memory_usage=268435456,read_overflow_mode='throw',group_by_overflow_mode='throw',optimize_move_to_prewhere_if_final=0"; + +/// Conservative heap accounting includes allocation slack/hash-table overhead, +/// retained samples, temporary batches, indexes and final output. Fail closed. +pub(crate) struct TopologyBudget { + pub(crate) max_bytes: usize, + used_bytes: usize, + max_entries: usize, + used_entries: usize, +} +impl Default for TopologyBudget { + fn default() -> Self { + Self::new(64 * 1024 * 1024, 100_000) + } +} +impl TopologyBudget { + pub(crate) fn new(max_bytes: usize, max_entries: usize) -> Self { + Self { + max_bytes, + used_bytes: 0, + max_entries, + used_entries: 0, + } + } + pub(crate) fn sample_limit(&self) -> usize { + self.max_bytes + .saturating_sub(self.used_bytes) + .saturating_sub(512) + / 4 + } + pub(crate) fn unlimited() -> Self { + Self::new(usize::MAX, usize::MAX) + } + pub(crate) fn reserve(&mut self, bytes: usize, entries: usize) -> Result<()> { + self.temporary(bytes)?; + let total = self + .used_entries + .checked_add(entries) + .ok_or_else(budget_error)?; + if total > self.max_entries { + return Err(budget_error()); + } + self.used_bytes += bytes; + self.used_entries = total; + Ok(()) + } + pub(crate) fn temporary(&self, bytes: usize) -> Result<()> { + if self + .used_bytes + .checked_add(bytes) + .is_none_or(|n| n > self.max_bytes) + { + return Err(budget_error()); + } + Ok(()) + } +} +fn budget_error() -> AppError { + AppError::Storage("ClickHouse topology aggregation budget exceeded".into()) +} +pub(crate) fn string_bytes(s: &str) -> usize { + s.len().saturating_mul(4) +} +pub(crate) fn strings_bytes(values: &[String]) -> usize { + values + .iter() + .map(|s| string_bytes(s)) + .sum::() + .saturating_add(values.len() * size_of::() * 4) +} +fn count_add(count: &mut u64, delta: u64) -> Result<()> { + *count = count + .checked_add(delta) + .ok_or_else(|| AppError::Storage("ClickHouse topology count overflow".into()))?; + Ok(()) +} + +#[derive(Row, Deserialize)] +struct NodeRow { + server_ip: String, + server_port: u16, + models: Vec, + request_paths: Vec, + call_count: u64, +} +#[derive(Row, Deserialize)] +struct TurnRow { + start_time: i64, + proxy_role: String, + pair_id: String, + first_call_id: String, +} +#[derive(Row, Deserialize)] +struct EndpointRow { + request_time: i64, + id: String, + server_ip: String, + server_port: u16, + client_ip: String, +} + +type Endpoint = (String, u16); +type Edge = (String, u16, String, u16); +type Entry = (String, String, u16); +#[derive(Default)] +struct PairCounts { + inbound: HashMap, + outbound: HashMap, +} +#[derive(Default)] +struct TurnCounts { + pairs: HashMap, + entries: HashMap, +} + +/// Matches parse_json_string_list's reject-whole-array contract. In particular, +/// CH's Array(String) coercions and leading-BOM acceptance are not serde's. +pub(crate) fn first_call_id_sql() -> &'static str { + "if(isValidJSON(span_ids) AND NOT startsWith(span_ids,unhex('EFBBBF')) \ + AND toString(JSONType(span_ids))='Array' \ + AND arrayAll(item -> toString(JSONType(item))='String',JSONExtractArrayRaw(span_ids)), \ + arrayElement(JSONExtract(span_ids,'Array(String)'),1),'')" +} + +impl ClickHouseBackend { + pub(crate) async fn query_services_topology( + &self, + query: &ServicesTopologyQuery, + ) -> Result { + self.topology_with_budget(query, TopologyBudget::default()) + .await + } + + pub(crate) async fn topology_with_budget( + &self, + query: &ServicesTopologyQuery, + mut budget: TopologyBudget, + ) -> Result { + let start = query.time_range.start_us; + let end = query.time_range.end_us; + let samples = self.fetch_app_samples(start, end, &mut budget).await?; + let where_sql = time_where("request_time", start, end); + let sql=format!("SELECT server_ip,server_port,groupUniqArray(32)(model) AS models,groupUniqArray(16)(request_path) AS request_paths,count() AS call_count FROM spans WHERE {where_sql} GROUP BY server_ip,server_port SETTINGS {QUERY_LIMITS}"); + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("topology nodes", e))?; + let mut nodes = Vec::new(); + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("topology nodes", e))? + { + budget.temporary( + 256 + string_bytes(&row.server_ip) + + strings_bytes(&row.models) + + strings_bytes(&row.request_paths), + )?; + let sample = samples.get(&(row.server_ip.clone(), row.server_port)); + let paths = sample + .filter(|s| !s.request_paths.is_empty()) + .map(|s| s.request_paths.as_slice()) + .unwrap_or(&row.request_paths); + let reasons = sample.map(|s| s.finish_reasons.as_slice()).unwrap_or(&[]); + let response_headers = sample.and_then(|s| s.sample_response_headers.as_deref()); + let header = extract_server_header(response_headers); + let app = classify_app( + header.as_deref(), + response_headers, + sample.and_then(|s| s.sample_request_headers.as_deref()), + paths, + reasons, + &row.models, + sample.and_then(|s| s.sample_request_body.as_deref()), + sample.and_then(|s| s.sample_response_body.as_deref()), + ); + budget.reserve( + 256 + string_bytes(&row.server_ip) + + strings_bytes(&row.models) + + app.as_deref().map_or(0, string_bytes), + 1, + )?; + nodes.push(TopologyNode { + server_ip: row.server_ip, + server_port: row.server_port, + models: row.models, + call_count: row.call_count, + app, + }); + } + drop(stream); + drop(samples); + + let sql=format!("SELECT start_time,JSONExtractString(coalesce(metadata,''),'proxy','role') AS proxy_role,JSONExtractString(coalesce(metadata,''),'proxy','pair_id') AS pair_id,{} AS first_call_id FROM traces FINAL WHERE {} ORDER BY start_time ASC,turn_id ASC SETTINGS {QUERY_LIMITS}",first_call_id_sql(),time_where("start_time",start,end)); + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("topology turns", e))?; + let mut batch = Vec::with_capacity(BATCH_ROWS); + let mut batch_bytes = BATCH_ROWS * size_of::() * 2; + let mut counts = TurnCounts::default(); + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("topology turns", e))? + { + batch_bytes = batch_bytes.saturating_add( + string_bytes(&row.proxy_role) + + string_bytes(&row.pair_id) + + string_bytes(&row.first_call_id), + ); + budget.temporary(batch_bytes)?; + batch.push(row); + if batch.len() == BATCH_ROWS { + self.accumulate_topology_batch(&batch, batch_bytes, &mut counts, &mut budget) + .await?; + batch.clear(); + batch_bytes = BATCH_ROWS * size_of::() * 2; + } + } + drop(stream); + if !batch.is_empty() { + self.accumulate_topology_batch(&batch, batch_bytes, &mut counts, &mut budget) + .await?; + } + drop(batch); + finish_graph(nodes, counts, &mut budget) + } + + async fn accumulate_topology_batch( + &self, + batch: &[TurnRow], + batch_bytes: usize, + counts: &mut TurnCounts, + budget: &mut TopologyBudget, + ) -> Result<()> { + let mut keys: Vec<_> = batch + .iter() + .filter(|r| !r.first_call_id.is_empty()) + .map(|r| (r.start_time, r.first_call_id.as_str())) + .collect(); + keys.sort_unstable(); + keys.dedup(); + if keys.is_empty() { + return Ok(()); + } + let first = keys.first().unwrap().0; + let last = keys.last().unwrap().0; + let tuples = keys + .iter() + .map(|(at, id)| format!("(fromUnixTimestamp64Micro({at}),'{}')", escape_str(id))) + .collect::>() + .join(","); + let sql=format!("SELECT request_time,id,server_ip,server_port,client_ip FROM spans WHERE request_time >= fromUnixTimestamp64Micro({first}) AND request_time <= fromUnixTimestamp64Micro({last}) AND (request_time,id) IN ({tuples}) SETTINGS {QUERY_LIMITS}"); + budget.temporary(batch_bytes.saturating_add(tuples.len() * 4))?; + let mut stream = self + .client + .query(&sql) + .fetch::() + .map_err(|e| ch_err("topology endpoints", e))?; + let mut endpoints = HashMap::new(); + let mut temporary = batch_bytes.saturating_add(tuples.len() * 4); + while let Some(row) = stream + .next() + .await + .map_err(|e| ch_err("topology endpoints", e))? + { + let key = (row.request_time, row.id); + if !endpoints.contains_key(&key) { + temporary = temporary.saturating_add( + 256 + string_bytes(&key.1) + + string_bytes(&row.server_ip) + + string_bytes(&row.client_ip), + ); + budget.temporary(temporary)?; + } + endpoints.insert(key, (row.server_ip, row.server_port, row.client_ip)); + } + for row in batch { + let Some((ip, port, caller)) = + endpoints.get(&(row.start_time, row.first_call_id.clone())) + else { + continue; + }; + if row.proxy_role != "proxy_out" { + let entry = (caller.clone(), ip.clone(), *port); + if !counts.entries.contains_key(&entry) { + budget.reserve(256 + string_bytes(caller) + string_bytes(ip), 1)?; + } + count_add(counts.entries.entry(entry).or_default(), 1)?; + } + if !row.pair_id.is_empty() + && matches!(row.proxy_role.as_str(), "proxy_in" | "proxy_out") + { + if !counts.pairs.contains_key(&row.pair_id) { + budget.reserve(256 + string_bytes(&row.pair_id), 1)?; + } + let pair = counts.pairs.entry(row.pair_id.clone()).or_default(); + let side = if row.proxy_role == "proxy_in" { + &mut pair.inbound + } else { + &mut pair.outbound + }; + let endpoint = (ip.clone(), *port); + if !side.contains_key(&endpoint) { + budget.reserve(256 + string_bytes(ip), 1)?; + } + count_add(side.entry(endpoint).or_default(), 1)?; + } + budget.temporary(temporary)?; + } + Ok(()) + } +} + +fn is_proxy(app: Option<&str>) -> bool { + matches!(app, Some("litellm" | "haproxy" | "nginx")) +} +fn resolve_caller( + nodes: &[TopologyNode], + by_ip: &HashMap<&str, Vec>, + caller: &str, + to_ip: &str, + to_port: u16, +) -> Option { + if by_ip + .get(to_ip) + .into_iter() + .flatten() + .map(|i| &nodes[*i]) + .any(|n| n.server_port == to_port && is_proxy(n.app.as_deref())) + { + return None; + } + let usable = || { + by_ip + .get(caller) + .into_iter() + .flatten() + .map(|i| &nodes[*i]) + .filter(|n| n.server_ip != to_ip || n.server_port != to_port) + }; + let selected = usable() + .find(|n| n.app.as_deref() == Some("litellm")) + .or_else(|| usable().find(|n| is_proxy(n.app.as_deref()))) + .or_else(|| usable().max_by_key(|n| n.call_count))?; + Some((selected.server_ip.clone(), selected.server_port)) +} +fn add_edge( + map: &mut HashMap, + edge: Edge, + count: u64, + budget: &mut TopologyBudget, +) -> Result<()> { + if !map.contains_key(&edge) { + budget.reserve(256 + string_bytes(&edge.0) + string_bytes(&edge.2), 1)?; + } + count_add(map.entry(edge).or_default(), count) +} +fn push_edge( + edges: &mut Vec, + edge: Edge, + count: u64, + kind: &str, + budget: &mut TopologyBudget, +) -> Result<()> { + budget.reserve( + 256 + string_bytes(&edge.0) + string_bytes(&edge.2) + string_bytes(kind), + 1, + )?; + edges.push(TopologyEdge { + from_ip: edge.0, + from_port: edge.1, + to_ip: edge.2, + to_port: edge.3, + turn_count: count, + kind: kind.into(), + }); + Ok(()) +} +fn finish_graph( + mut nodes: Vec, + counts: TurnCounts, + budget: &mut TopologyBudget, +) -> Result { + let mut proxy = HashMap::new(); + for pair in counts.pairs.values() { + for ((from, fp), a) in &pair.inbound { + for ((to, tp), b) in &pair.outbound { + if from == to && fp == tp { + continue; + } + let count = a.checked_mul(*b).ok_or_else(|| { + AppError::Storage("ClickHouse topology count overflow".into()) + })?; + add_edge( + &mut proxy, + (from.clone(), *fp, to.clone(), *tp), + count, + budget, + )?; + } + } + } + let mut by_ip: HashMap<&str, Vec> = HashMap::new(); + for (i, node) in nodes.iter().enumerate() { + budget.reserve(128, 1)?; + by_ip.entry(&node.server_ip).or_default().push(i); + } + let mut inferred = HashMap::new(); + let mut clients: HashMap = HashMap::new(); + for ((caller, to, tp), count) in counts.entries { + if let Some((from, fp)) = resolve_caller(&nodes, &by_ip, &caller, &to, tp) { + let edge = (from, fp, to, tp); + if !proxy.contains_key(&edge) { + add_edge(&mut inferred, edge, count, budget)?; + } + } else { + let endpoint = (to, tp); + if !clients.contains_key(&endpoint) { + budget.reserve(256 + string_bytes(&endpoint.0), 1)?; + } + count_add(clients.entry(endpoint).or_default(), count)?; + } + } + drop(by_ip); + let mut edges = Vec::new(); + for (edge, count) in proxy { + push_edge(&mut edges, edge, count, "proxy", budget)?; + } + for (edge, count) in inferred { + push_edge(&mut edges, edge, count, "inferred", budget)?; + } + let mut client_total = 0; + for ((to, tp), count) in clients { + count_add(&mut client_total, count)?; + push_edge( + &mut edges, + ("__clients__".into(), 0, to, tp), + count, + "client", + budget, + )?; + } + if client_total > 0 { + budget.reserve(512, 1)?; + nodes.push(TopologyNode { + server_ip: "__clients__".into(), + server_port: 0, + app: Some("clients".into()), + models: Vec::new(), + call_count: client_total, + }); + } + Ok(ServicesTopology { nodes, edges }) +} diff --git a/server/h-storage-clickhouse/src/turns.rs b/server/h-storage-clickhouse/src/turns.rs index 0669368c..1862e296 100644 --- a/server/h-storage-clickhouse/src/turns.rs +++ b/server/h-storage-clickhouse/src/turns.rs @@ -2,9 +2,9 @@ //! support (`query_pair_candidates` / `update_trace_metadata`). //! //! `traces` is `ReplacingMergeTree(_version)`: it is the only mutated -//! table. Writes insert with `_version = end_time` (micros); reads use `FINAL`; +//! authoritative table. Writes insert with `_version = end_time` (micros); reads use `FINAL`; //! `update_trace_metadata` reads the full row (FINAL), merges the JSON patch, and -//! re-inserts the whole row with a wall-clock-micros `_version` so the latest +//! re-inserts the whole row with a checked strictly increasing `_version` so the latest //! metadata wins on the next FINAL read. use std::time::{SystemTime, UNIX_EPOCH}; @@ -26,7 +26,7 @@ use crate::ClickHouseBackend; /// `DateTime64(6)` columns surfaced as `i64` micros so they deserialize into /// `TurnRow`'s `i64` fields and round-trip on re-insert. Used by /// `update_trace_metadata`'s read-modify-write. -const TURN_ROW_SELECT: &str = "turn_id, source_id, session_id, wire_api, agent_kind, \ +pub(crate) const TURN_ROW_SELECT: &str = "turn_id, source_id, session_id, wire_api, agent_kind, \ client_ip, server_ip, \ toUnixTimestamp64Micro(start_time) AS start_time, \ toUnixTimestamp64Micro(end_time) AS end_time, \ @@ -69,7 +69,7 @@ fn extract_proxy_fields( (role, peer_id, peer_ids) } -fn now_micros() -> u64 { +pub(crate) fn now_micros() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_micros() as u64) @@ -137,23 +137,6 @@ struct TraceDetailRow { suspicious_skills_json: Option, } -#[derive(Row, Deserialize)] -struct PairCandidateRow { - turn_id: String, - session_id: String, - agent_kind: String, - wire_api: String, - start_time_us: i64, - end_time_us: i64, - call_count: u32, - total_input_tokens: u64, - total_output_tokens: u64, - final_finish_reason: Option, - models_used: Option, - client_ip: String, - server_ip: String, -} - #[derive(Row, Deserialize)] struct CountRow { n: u64, @@ -405,45 +388,7 @@ impl ClickHouseBackend { start_us: i64, end_us: i64, ) -> Result> { - let ts_pred = time_where("start_time", start_us, end_us); - let sql = format!( - "SELECT turn_id, session_id, agent_kind, wire_api, \ - toUnixTimestamp64Micro(start_time) AS start_time_us, \ - toUnixTimestamp64Micro(end_time) AS end_time_us, \ - call_count, total_input_tokens, total_output_tokens, \ - final_finish_reason, models_used, client_ip, server_ip \ - FROM traces FINAL \ - WHERE {ts_pred} \ - AND JSONExtractString(coalesce(metadata, ''), 'proxy', 'role') = '' \ - ORDER BY start_time ASC" - ); - let rows = self - .client - .query(&sql) - .fetch_all::() - .await - .map_err(|e| ch_err("query_pair_candidates", e))?; - Ok(rows - .into_iter() - .map(|r| { - let models = parse_json_string_list(r.models_used.as_deref()); - let primary_model = models.first().cloned(); - PairCandidate { - turn_id: r.turn_id, - session_id: r.session_id, - agent_kind: r.agent_kind, - wire_api: r.wire_api, - start_time_us: r.start_time_us, - end_time_us: r.end_time_us, - call_count: r.call_count, - total_input_tokens: r.total_input_tokens, - total_output_tokens: r.total_output_tokens, - final_finish_reason: r.final_finish_reason, - primary_model, - network_view: format!("{}->{}", r.client_ip, r.server_ip), - } - }) - .collect()) + self.indexed_pair_candidates(start_us, end_us).await } pub(crate) async fn update_trace_metadata( @@ -451,9 +396,10 @@ impl ClickHouseBackend { turn_id: &str, patch: serde_json::Value, ) -> Result<()> { + let _gate = self.pairing_gate.lock().await; // Read-modify-write on ReplacingMergeTree: fetch the current full row // (FINAL = latest version), shallow-merge the patch into metadata, and - // re-insert with a strictly-greater `_version` (wall-clock micros). + // re-insert with a checked strictly-greater `_version`. let sql = format!( "SELECT {TURN_ROW_SELECT} FROM traces FINAL WHERE turn_id = '{}' LIMIT 1", escape_str(turn_id) @@ -471,23 +417,33 @@ impl ClickHouseBackend { return Ok(()); }; - let mut base = row - .metadata - .as_deref() - .and_then(|s| serde_json::from_str::(s).ok()) - .unwrap_or_else(|| serde_json::json!({})); - if !base.is_object() { - base = serde_json::json!({}); - } - if let (Some(obj), Some(patch_obj)) = (base.as_object_mut(), patch.as_object()) { - for (k, v) in patch_obj { - obj.insert(k.clone(), v.clone()); - } - } - row.metadata = Some(base.to_string()); - row._version = now_micros(); + row.metadata = Some(merge_trace_metadata(row.metadata.as_deref(), &patch)); + row._version = next_trace_version(row._version, now_micros())?; insert_all!(self.client, "traces", TurnRow, vec![row]); + #[cfg(test)] + self.pairing_faults.trace_chunk()?; Ok(()) } } + +/// Never let a metadata update lose to a source clock in the future. +pub(crate) fn next_trace_version(previous: u64, now: u64) -> Result { + let next = previous + .checked_add(1) + .ok_or_else(|| AppError::Storage("ClickHouse trace metadata version exhausted".into()))?; + Ok(now.max(next)) +} + +pub(crate) fn merge_trace_metadata(current: Option<&str>, patch: &serde_json::Value) -> String { + let mut base = current + .and_then(|s| serde_json::from_str::(s).ok()) + .filter(|v| v.is_object()) + .unwrap_or_else(|| serde_json::json!({})); + if let (Some(base), Some(patch)) = (base.as_object_mut(), patch.as_object()) { + for (key, value) in patch { + base.insert(key.clone(), value.clone()); + } + } + base.to_string() +} diff --git a/server/h-storage-duckdb/Cargo.toml b/server/h-storage-duckdb/Cargo.toml index af25e662..2d701621 100644 --- a/server/h-storage-duckdb/Cargo.toml +++ b/server/h-storage-duckdb/Cargo.toml @@ -16,6 +16,9 @@ async-trait.workspace = true tokio.workspace = true tracing.workspace = true serde_json.workspace = true +serde.workspace = true +sha2 = "0.10" +libc.workspace = true chrono.workspace = true bytes.workspace = true @@ -23,6 +26,10 @@ bytes.workspace = true tempfile = "3" [features] +# Standalone builds/tests bundle DuckDB unless explicitly disabled. +default = ["bundled-duckdb"] +bundled-duckdb = ["duckdb/bundled", "duckdb/json"] + # Enables `fault_injection` module + injection hooks on backend paths. # Off by default: production builds and `cargo test --workspace` see # no extra code. Tests that exercise recovery paths opt in explicitly. diff --git a/server/h-storage-duckdb/src/calls.rs b/server/h-storage-duckdb/src/calls.rs index 06ce5aa6..a7e47da1 100644 --- a/server/h-storage-duckdb/src/calls.rs +++ b/server/h-storage-duckdb/src/calls.rs @@ -7,8 +7,10 @@ use h_common::process::ProcessInfo; use h_llm::model::LlmCall; use h_storage::query::*; +use crate::journal::Journal; use crate::util::{ - derive_tokens_estimated, headers_to_json, parse_json_string_list, us_to_timestamp, + derive_tokens_estimated, headers_to_json, hydrate_span_payload, parse_json_string_list, + us_to_timestamp, }; use crate::DuckDbBackend; @@ -140,12 +142,8 @@ fn read_calls_by_ids_sync( let placeholders = std::iter::repeat_n("?", span_ids.len()) .collect::>() .join(", "); - // Lite mode (`include_bodies = false`) selects `NULL` for the four - // heavy fields directly in SQL, so DuckDB never reads the body - // pages off disk and the rows never need to be transferred to - // Rust as Strings. The downstream `tokens_estimated` derivation - // falls back to `false` when response_body is missing — documented - // on `StorageBackend::query_trace_spans`. + // Lite mode selects NULL for payload fields and only consults the indexed + // token-estimation flag; it never opens a journal payload segment. let body_columns: &str = if include_bodies { "request_body, response_body, request_headers, response_headers" } else { @@ -168,7 +166,7 @@ fn read_calls_by_ids_sync( {body_columns} FROM spans WHERE id IN ({placeholders}) - ORDER BY request_time ASC, complete_time ASC" + ORDER BY request_time ASC, complete_time ASC, id ASC" ); let mut stmt = conn @@ -262,15 +260,77 @@ fn read_calls_by_ids_sync( .map_err(|e| AppError::Storage(format!("read error: {e}")))?, }); let last = items.last_mut().expect("just pushed"); - last.tokens_estimated = derive_tokens_estimated( - last.input_tokens, - last.output_tokens, - last.response_body.as_deref(), - ); + let estimated = if include_bodies { + match hydrate_span_payload(conn, &last.id)? { + Some(payload) => { + last.request_body = payload.request_body; + last.response_body = payload.response_body; + last.request_headers = payload.request_headers; + last.response_headers = payload.response_headers; + Some(payload.tokens_estimated) + } + None => None, + } + } else { + Journal::estimated(conn, &last.id)? + }; + last.tokens_estimated = estimated.unwrap_or_else(|| { + derive_tokens_estimated( + last.input_tokens, + last.output_tokens, + last.response_body.as_deref(), + ) + }); } Ok(items) } +impl PreparedCall { + fn parameters(&self) -> Vec<&dyn duckdb::ToSql> { + let p = self; + vec![ + &p.id, + &p.source_id, + &p.client_ip, + &p.client_port, + &p.server_ip, + &p.server_port, + &p.request_time, + &p.response_time, + &p.complete_time, + &p.wire_api, + &p.model, + &p.api_type, + &p.is_stream, + &p.request_path, + &p.status_code, + &p.finish_reason, + &p.input_tokens, + &p.output_tokens, + &p.total_tokens, + &p.cache_read_input_tokens, + &p.cache_creation_input_tokens, + &p.ttft_ms, + &p.e2e_latency_ms, + &p.request_body, + &p.response_body, + &p.response_id, + &p.request_headers, + &p.response_headers, + &p.is_agent_request, + &p.tool_surface, + &p.agent_topology, + &p.tool_call_count, + &p.tool_names_json, + &p.body_bytes_dropped, + &p.process_pid, + &p.process_comm, + &p.process_exe, + &"llm", + ] + } +} + impl DuckDbBackend { pub(crate) async fn write_spans(&self, calls: Vec) -> Result<()> { if calls.is_empty() { @@ -287,11 +347,20 @@ impl DuckDbBackend { } } let conn = self.write_spans_conn.clone(); + let journal = self.journal.clone(); tokio::task::spawn_blocking(move || { // Serialize/format outside the writer Mutex so the lock is held // only for the append + flush. let prepared: Vec = calls.into_iter().map(prepare_call).collect(); + if let Some(journal) = journal { + let rows = prepared + .iter() + .map(|p| crate::journal::row(crate::journal::Table::Spans, &p.parameters())) + .collect::>>()?; + return journal.append(rows); + } + let conn = conn .lock() .map_err(|e| AppError::Storage(format!("failed to lock writer: {e}")))?; @@ -300,49 +369,7 @@ impl DuckDbBackend { .map_err(|e| AppError::Storage(format!("failed to create appender: {e}")))?; for p in &prepared { appender - .append_row(duckdb::params![ - p.id, - p.source_id, - p.client_ip, - p.client_port, - p.server_ip, - p.server_port, - p.request_time, - p.response_time, - p.complete_time, - p.wire_api, - p.model, - p.api_type, - p.is_stream, - p.request_path, - p.status_code, - p.finish_reason, - p.input_tokens, - p.output_tokens, - p.total_tokens, - p.cache_read_input_tokens, - p.cache_creation_input_tokens, - p.ttft_ms, - p.e2e_latency_ms, - p.request_body, - p.response_body, - p.response_id, - p.request_headers, - p.response_headers, - p.is_agent_request, - p.tool_surface, - p.agent_topology, - p.tool_call_count, - p.tool_names_json, - p.body_bytes_dropped, - p.process_pid, - p.process_comm, - p.process_exe, - // `kind` (tail column). Every wire-captured span is an - // LLM call today; written as a literal so the domain - // model stays free of a field that has one value. - "llm", - ]) + .append_row(p.parameters().as_slice()) .map_err(|e| AppError::Storage(format!("failed to append call: {e}")))?; } appender @@ -515,8 +542,12 @@ impl DuckDbBackend { let response_body: Option = row .get(16) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; - let tokens_estimated = - derive_tokens_estimated(input_tokens, output_tokens, response_body.as_deref()); + let id: String = row + .get(0) + .map_err(|e| AppError::Storage(format!("read error: {e}")))?; + let tokens_estimated = Journal::estimated(&conn, &id)?.unwrap_or_else(|| { + derive_tokens_estimated(input_tokens, output_tokens, response_body.as_deref()) + }); let tool_names_json: Option = row .get(21) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; @@ -527,9 +558,7 @@ impl DuckDbBackend { let process = read_process(row, 22, 23, 24) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; items.push(SpanListItem { - id: row - .get(0) - .map_err(|e| AppError::Storage(format!("read error: {e}")))?, + id, source_id: row .get(1) .map_err(|e| AppError::Storage(format!("read error: {e}")))?, @@ -677,7 +706,16 @@ impl DuckDbBackend { }); match result { - Ok(detail) => Ok(Some(detail)), + Ok(mut detail) => { + if let Some(payload) = hydrate_span_payload(&conn, &id)? { + detail.request_body = payload.request_body; + detail.response_body = payload.response_body; + detail.request_headers = payload.request_headers; + detail.response_headers = payload.response_headers; + detail.tokens_estimated = payload.tokens_estimated; + } + Ok(Some(detail)) + } Err(duckdb::Error::QueryReturnedNoRows) => Ok(None), Err(e) => Err(AppError::Storage(format!( "failed to query call by id: {e}" diff --git a/server/h-storage-duckdb/src/exchanges.rs b/server/h-storage-duckdb/src/exchanges.rs index 114cf407..6833e85c 100644 --- a/server/h-storage-duckdb/src/exchanges.rs +++ b/server/h-storage-duckdb/src/exchanges.rs @@ -5,7 +5,8 @@ use h_common::error::{AppError, Result}; use h_protocol::HttpExchange; use h_storage::query::*; -use crate::util::{headers_to_json, render_body_for_detail, us_to_timestamp}; +use crate::journal::{Journal, Table}; +use crate::util::{headers_to_json, payload_utf8, render_body_for_detail, us_to_timestamp}; use crate::DuckDbBackend; struct PreparedExchange { @@ -69,6 +70,33 @@ fn prepare_exchange(x: HttpExchange) -> PreparedExchange { } } +impl PreparedExchange { + fn parameters(&self) -> Vec<&dyn duckdb::ToSql> { + let p = self; + vec![ + &p.id, + &p.source_id, + &p.client_ip, + &p.client_port, + &p.server_ip, + &p.server_port, + &p.method, + &p.uri, + &p.request_headers, + &p.request_body, + &p.status, + &p.response_headers, + &p.response_body, + &p.is_sse, + &p.sse_event_count, + &p.sse_data_bytes, + &p.request_time, + &p.response_first_byte_time, + &p.response_complete_time, + ] + } +} + impl DuckDbBackend { pub(crate) async fn write_exchanges(&self, exchanges: Vec) -> Result<()> { if exchanges.is_empty() { @@ -85,10 +113,19 @@ impl DuckDbBackend { } } let conn = self.write_exchanges_conn.clone(); + let journal = self.journal.clone(); tokio::task::spawn_blocking(move || { let prepared: Vec = exchanges.into_iter().map(prepare_exchange).collect(); + if let Some(journal) = journal { + let rows = prepared + .iter() + .map(|p| crate::journal::row(crate::journal::Table::Exchanges, &p.parameters())) + .collect::>>()?; + return journal.append(rows); + } + let conn = conn .lock() .map_err(|e| AppError::Storage(format!("failed to lock writer: {e}")))?; @@ -97,27 +134,7 @@ impl DuckDbBackend { .map_err(|e| AppError::Storage(format!("failed to create appender: {e}")))?; for p in &prepared { appender - .append_row(duckdb::params![ - p.id, - p.source_id, - p.client_ip, - p.client_port, - p.server_ip, - p.server_port, - p.method, - p.uri, - p.request_headers, - p.request_body, - p.status, - p.response_headers, - p.response_body, - p.is_sse, - p.sse_event_count, - p.sse_data_bytes, - p.request_time, - p.response_first_byte_time, - p.response_complete_time, - ]) + .append_row(p.parameters().as_slice()) .map_err(|e| AppError::Storage(format!("failed to append exchange: {e}")))?; } appender @@ -178,7 +195,17 @@ impl DuckDbBackend { }) }); match result { - Ok(d) => Ok(Some(d)), + Ok(mut detail) => { + if let Some(payload) = Journal::hydrate(&conn, Table::Exchanges, &id)? { + detail.request_body = render_body_for_detail(payload.request_body); + detail.response_body = render_body_for_detail(payload.response_body); + detail.request_headers = payload_utf8(payload.request_headers)? + .unwrap_or_else(|| "[]".to_string()); + detail.response_headers = payload_utf8(payload.response_headers)? + .unwrap_or_else(|| "[]".to_string()); + } + Ok(Some(detail)) + } Err(duckdb::Error::QueryReturnedNoRows) => Ok(None), Err(e) => Err(AppError::Storage(format!( "failed to query http_exchange by id: {e}" diff --git a/server/h-storage-duckdb/src/journal.rs b/server/h-storage-duckdb/src/journal.rs new file mode 100644 index 00000000..f765ba12 --- /dev/null +++ b/server/h-storage-duckdb/src/journal.rs @@ -0,0 +1,1984 @@ +//! Durable full-record journal with an independently replayed DuckDB index. +//! +//! A successful append means payload and metadata are synced, not indexed. +//! The index worker owns no backend/Journal Arc and reads only bounded metadata +//! frames. Its cursor commits in the same transaction as the projected rows. + +use std::collections::{HashMap, VecDeque}; +use std::fs::{self, File, OpenOptions}; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, TryLockError}; +use std::thread::JoinHandle; +use std::time::Duration; + +use duckdb::types::{TimeUnit, ToSqlOutput, Value, ValueRef}; +use duckdb::{Connection, ToSql}; +use h_common::error::{AppError, Result}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tokio::sync::Notify; + +const SEGMENT_LIMIT: u64 = 64 * 1024 * 1024; +const METADATA_TARGET: usize = 256 * 1024; +// A large Trace projection is a legitimate single record. Keep the usual +// index batch small while bounding allocations for corrupt/hostile framing. +const MAX_METADATA: usize = 16 * 1024 * 1024; +const MAX_ROWS: usize = 100; +const DEDUP_ENTRIES: usize = 8192; +const HEADER_LEN: usize = 88; +const RECORD_MAGIC: [u8; 4] = *b"HRM1"; +const PAYLOAD_MAGIC: [u8; 4] = *b"HRP1"; +const DRAIN_TIMEOUT: Duration = Duration::from_secs(30); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub(crate) enum Table { + Spans, + Exchanges, + Traces, + Metrics, + FinishMetrics, +} + +impl Table { + fn name(self) -> &'static str { + match self { + Self::Spans => "spans", + Self::Exchanges => "http_exchanges", + Self::Traces => "traces", + Self::Metrics => "llm_metrics", + Self::FinishMetrics => "llm_finish_metrics", + } + } + + // Request body, response body, request headers, response headers. + fn payload_columns(self) -> Option<[usize; 4]> { + match self { + Self::Spans => Some([23, 24, 26, 27]), + Self::Exchanges => Some([9, 12, 8, 11]), + _ => None, + } + } +} + +#[derive(Debug, Serialize, Deserialize)] +enum Cell { + Null, + Bool(bool), + I64(i64), + U64(u64), + F64(f64), + Text(String), + Blob(Vec), + Timestamp(StampUnit, i64), +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +enum StampUnit { + Second, + Millisecond, + Microsecond, + Nanosecond, +} + +impl Cell { + fn from_value(value: ValueRef<'_>) -> Result { + Ok(match value { + ValueRef::Null => Self::Null, + ValueRef::Boolean(v) => Self::Bool(v), + ValueRef::TinyInt(v) => Self::I64(v.into()), + ValueRef::SmallInt(v) => Self::I64(v.into()), + ValueRef::Int(v) => Self::I64(v.into()), + ValueRef::BigInt(v) => Self::I64(v), + ValueRef::UTinyInt(v) => Self::U64(v.into()), + ValueRef::USmallInt(v) => Self::U64(v.into()), + ValueRef::UInt(v) => Self::U64(v.into()), + ValueRef::UBigInt(v) => Self::U64(v), + ValueRef::Float(v) if v.is_finite() => Self::F64(v.into()), + ValueRef::Double(v) if v.is_finite() => Self::F64(v), + ValueRef::Text(v) => Self::Text(String::from_utf8(v.to_vec()).map_err(storage)?), + ValueRef::Blob(v) => Self::Blob(v.to_vec()), + ValueRef::Timestamp(unit, v) => Self::Timestamp( + match unit { + TimeUnit::Second => StampUnit::Second, + TimeUnit::Millisecond => StampUnit::Millisecond, + TimeUnit::Microsecond => StampUnit::Microsecond, + TimeUnit::Nanosecond => StampUnit::Nanosecond, + }, + v, + ), + other => return Err(storage(format!("unsupported journal SQL value: {other:?}"))), + }) + } + + fn sql_value(&self) -> Value { + match self { + Self::Null => Value::Null, + Self::Bool(v) => Value::Boolean(*v), + Self::I64(v) => Value::BigInt(*v), + Self::U64(v) => Value::UBigInt(*v), + Self::F64(v) => Value::Double(*v), + Self::Text(v) => Value::Text(v.clone()), + Self::Blob(v) => Value::Blob(v.clone()), + Self::Timestamp(unit, v) => Value::Timestamp( + match unit { + StampUnit::Second => TimeUnit::Second, + StampUnit::Millisecond => TimeUnit::Millisecond, + StampUnit::Microsecond => TimeUnit::Microsecond, + StampUnit::Nanosecond => TimeUnit::Nanosecond, + }, + *v, + ), + } + } + + fn token_count(&self) -> Option { + match self { + Self::I64(v) => (*v).try_into().ok(), + Self::U64(v) => (*v).try_into().ok(), + _ => None, + } + } +} + +/// Owns its SQL values; does not retain parameter references or domain objects. +#[derive(Debug, Serialize, Deserialize)] +pub(crate) struct Row { + table: Table, + cells: Vec, + payloads: Option, + tokens_estimated: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct PayloadRef { + segment: u64, + offset: u64, + length: u64, + hash: [u8; 32], +} + +#[derive(Debug, Default, Serialize, Deserialize)] +struct Refs { + request_body: Option, + response_body: Option, + request_headers: Option, + response_headers: Option, +} + +impl Refs { + fn all(&self) -> [&Option; 4] { + [ + &self.request_body, + &self.response_body, + &self.request_headers, + &self.response_headers, + ] + } +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) struct PayloadFields { + pub request_body: Option>, + pub response_body: Option>, + pub request_headers: Option>, + pub response_headers: Option>, + pub tokens_estimated: bool, +} + +#[derive(Debug, Clone)] +pub(crate) struct Status { + pub durable: u64, + pub indexed: u64, + pub last_error: Option, +} + +struct SharedState { + status: Status, + append_error: Option, +} + +struct Shared { + state: Mutex, + wake: Condvar, + progress: Notify, + stop: AtomicBool, +} + +impl Shared { + fn wait(&self, duration: Duration) { + let state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if !self.stop.load(Ordering::Acquire) { + let _ = self.wake.wait_timeout(state, duration); + } + } + + fn index_result(&self, result: std::result::Result) { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + match result { + Ok(sequence) => { + state.status.indexed = sequence; + if state.append_error.is_none() { + state.status.last_error = None; + } + } + Err(error) => { + if state.append_error.is_none() { + state.status.last_error = Some(error); + } + } + } + self.progress.notify_waiters(); + } +} + +struct SegmentWriter { + directory: PathBuf, + prefix: &'static str, + segment: u64, + file: File, + position: u64, +} + +impl SegmentWriter { + fn new(directory: &Path, prefix: &'static str, segment: u64, position: u64) -> Result { + let path = segment_path(directory, prefix, segment); + let existed = path.exists(); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path) + .map_err(storage)?; + file.seek(SeekFrom::Start(position)).map_err(storage)?; + if !existed { + file.sync_all().map_err(storage)?; + sync_directory(directory)?; + } + Ok(Self { + directory: directory.into(), + prefix, + segment, + file, + position, + }) + } + + fn frame(&mut self, magic: [u8; 4], sequence: u64, bytes: &[u8]) -> Result { + let length = u64::try_from(bytes.len()).map_err(storage)?; + let frame_length = length + .checked_add(HEADER_LEN as u64) + .ok_or_else(|| storage("journal frame length overflow"))?; + if self.position > 0 && self.position.saturating_add(frame_length) > SEGMENT_LIMIT { + self.file.sync_all().map_err(storage)?; + let next = self + .segment + .checked_add(1) + .ok_or_else(|| storage("journal segment overflow"))?; + *self = Self::new(&self.directory, self.prefix, next, 0)?; + } + let hash: [u8; 32] = Sha256::digest(bytes).into(); + let header = header(magic, length, sequence, hash); + let offset = self.position + HEADER_LEN as u64; + self.file.write_all(&header).map_err(storage)?; + self.file.write_all(bytes).map_err(storage)?; + self.position = self + .position + .checked_add(frame_length) + .ok_or_else(|| storage("journal offset overflow"))?; + Ok(PayloadRef { + segment: self.segment, + offset, + length, + hash, + }) + } +} + +struct AppendState { + payload: SegmentWriter, + records: SegmentWriter, + sequence: u64, + dedup: HashMap<[u8; 32], PayloadRef>, + dedup_order: VecDeque<[u8; 32]>, + failure: Option, +} + +impl AppendState { + fn remember(&mut self, reference: PayloadRef) { + remember(&mut self.dedup, &mut self.dedup_order, reference); + } + + fn save_payload(&mut self, bytes: &[u8]) -> Result { + let hash: [u8; 32] = Sha256::digest(bytes).into(); + if let Some(reference) = self.dedup.get(&hash) { + if reference.length == bytes.len() as u64 { + return Ok(reference.clone()); + } + } + let reference = self.payload.frame(PAYLOAD_MAGIC, 0, bytes)?; + self.remember(reference.clone()); + Ok(reference) + } + + fn externalize(&mut self, mut row: Row) -> Result { + let Some(columns) = row.table.payload_columns() else { + return Ok(row); + }; + if row.table == Table::Spans { + let response = match row.cells.get(24) { + Some(Cell::Text(text)) => Some(text.as_str()), + _ => None, + }; + row.tokens_estimated = h_storage::convert::derive_tokens_estimated( + row.cells.get(16).and_then(Cell::token_count), + row.cells.get(17).and_then(Cell::token_count), + response, + ); + } + let mut refs = Vec::with_capacity(4); + for column in columns { + let cell = row + .cells + .get_mut(column) + .ok_or_else(|| storage("short journal payload row"))?; + let value = std::mem::replace(cell, Cell::Null); + let bytes = match value { + Cell::Null => None, + Cell::Text(text) => Some(text.into_bytes()), + Cell::Blob(bytes) => Some(bytes), + _ => return Err(storage("journal payload must be NULL, TEXT or BLOB")), + }; + refs.push( + bytes + .as_deref() + .map(|bytes| self.save_payload(bytes)) + .transpose()?, + ); + // HTTP headers are NOT NULL in the existing schema. Bodies and all + // span payload columns remain NULL in the small SQL projection. + if row.table == Table::Exchanges && (column == 8 || column == 11) { + *cell = Cell::Text("[]".into()); + } + } + let mut refs = refs.into_iter(); + row.payloads = Some(Refs { + request_body: refs.next().flatten(), + response_body: refs.next().flatten(), + request_headers: refs.next().flatten(), + response_headers: refs.next().flatten(), + }); + Ok(row) + } + + fn append(&mut self, rows: Vec) -> Result<()> { + // The sink journals wide+finish rows together. Preserve that logical + // metrics batch as one transaction, rather than splitting its pair at + // an arbitrary metadata byte/row boundary. + let preserve_batch = rows + .iter() + .any(|row| matches!(row.table, Table::Metrics | Table::FinishMetrics)); + let mut batches: Vec> = Vec::new(); + let mut pending = Vec::new(); + let mut pending_bytes = 128; + for row in rows { + let row = self.externalize(row)?; + let size = serde_json::to_vec(&row).map_err(storage)?.len(); + if size + 128 > MAX_METADATA { + return Err(storage( + "journal metadata row exceeds 16 MiB format bound; payload is retained", + )); + } + if !preserve_batch + && !pending.is_empty() + && (pending.len() >= MAX_ROWS || pending_bytes + size > METADATA_TARGET) + { + batches.push(std::mem::take(&mut pending)); + pending_bytes = 128; + } + if preserve_batch && pending_bytes + size + 1 > MAX_METADATA { + return Err(storage( + "journal atomic metrics batch exceeds 16 MiB format bound", + )); + } + pending_bytes += size + 1; + pending.push(row); + } + if !pending.is_empty() { + batches.push(pending); + } + // No metadata reference becomes durable before every referenced payload. + self.payload.file.sync_all().map_err(storage)?; + for rows in batches { + let sequence = self + .sequence + .checked_add(1) + .ok_or_else(|| storage("journal sequence overflow"))?; + let bytes = serde_json::to_vec(&Batch { sequence, rows }).map_err(storage)?; + if bytes.len() > MAX_METADATA { + return Err(storage("journal metadata batch exceeds bound")); + } + self.records.frame(RECORD_MAGIC, sequence, &bytes)?; + self.sequence = sequence; + } + self.records.file.sync_all().map_err(storage)?; + Ok(()) + } +} + +#[derive(Serialize, Deserialize)] +struct Batch { + sequence: u64, + rows: Vec, +} + +#[derive(Clone, Copy, Default)] +struct Cursor { + sequence: u64, + segment: u64, + offset: u64, +} + +pub(crate) struct Journal { + directory: PathBuf, + identity: String, + append: Mutex, + shared: Arc, + worker: Mutex>>, + // Released only after the worker joins in Drop. + _directory_lock: File, +} + +pub(crate) const AUXILIARY_SCHEMA: &str = " +CREATE TABLE IF NOT EXISTS _heron_journal_cursor ( + singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK(singleton), + journal_id VARCHAR NOT NULL, + sequence UBIGINT NOT NULL, + segment UBIGINT NOT NULL, + byte_offset UBIGINT NOT NULL +); +CREATE TABLE IF NOT EXISTS _heron_journal_payloads ( + entity VARCHAR NOT NULL, + id VARCHAR NOT NULL, + fields VARCHAR NOT NULL, + tokens_estimated BOOLEAN NOT NULL, + PRIMARY KEY(entity, id) +);"; + +/// Persistent ownership survives disabling append mode on an existing dataset. +pub(crate) fn owns_database(conn: &Connection) -> Result { + let exists: u64 = conn.query_row( + "SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '_heron_journal_cursor'", + [], |r| r.get(0), + ).map_err(storage)?; + if exists == 0 { + return Ok(false); + } + conn.query_row("SELECT COUNT(*) > 0 FROM _heron_journal_cursor", [], |r| { + r.get(0) + }) + .map_err(storage) +} + +/// Legacy mode initializes these too, so externally stored rows stay readable +/// after journal mode is disabled. No payload path is persisted in DuckDB. +pub(crate) fn init_schema(conn: &Connection) -> Result<()> { + conn.execute_batch(AUXILIARY_SCHEMA).map_err(storage) +} + +pub(crate) fn row(table: Table, params: &[&dyn ToSql]) -> Result { + let mut cells = Vec::with_capacity(params.len()); + for param in params { + let output = param.to_sql().map_err(storage)?; + let cell = match output { + ToSqlOutput::Borrowed(value) => Cell::from_value(value)?, + ToSqlOutput::Owned(value) => { + // The owned value must remain alive through its borrowed view. + match value.to_sql().map_err(storage)? { + ToSqlOutput::Borrowed(value) => Cell::from_value(value)?, + _ => return Err(storage("unsupported owned journal SQL value")), + } + } + _ => return Err(storage("unsupported journal SQL output")), + }; + cells.push(cell); + } + Ok(Row { + table, + cells, + payloads: None, + tokens_estimated: false, + }) +} + +impl Journal { + pub(crate) fn open(path: &Path) -> Result { + #[cfg(not(unix))] + return Err(storage("journal mode requires Unix directory locking")); + #[cfg(unix)] + { + fs::create_dir_all(path).map_err(storage)?; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + sync_directory(parent)?; + } + let directory_lock = OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(path.join("lock")) + .map_err(storage)?; + use std::os::fd::AsRawFd; + // SAFETY: the descriptor belongs to directory_lock and remains open + // until the worker has stopped; flock does not access Rust memory. + if unsafe { libc::flock(directory_lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } + != 0 + { + return Err(storage(format!( + "journal directory is already locked: {}", + std::io::Error::last_os_error() + ))); + } + let identity = identity(path, true)?; + let (payload_segment, payload_end, dedup, dedup_order) = recover_payloads(path)?; + let (record_segment, record_end, sequence) = recover_records(path)?; + let append = AppendState { + payload: SegmentWriter::new(path, "payload-", payload_segment, payload_end)?, + records: SegmentWriter::new(path, "records-", record_segment, record_end)?, + sequence, + dedup, + dedup_order, + failure: None, + }; + Ok(Self { + directory: path.into(), + identity, + append: Mutex::new(append), + shared: Arc::new(Shared { + state: Mutex::new(SharedState { + status: Status { + durable: sequence, + indexed: 0, + last_error: None, + }, + append_error: None, + }), + wake: Condvar::new(), + progress: Notify::new(), + stop: AtomicBool::new(false), + }), + worker: Mutex::new(None), + _directory_lock: directory_lock, + }) + } + } + + pub(crate) fn append(&self, rows: Vec) -> Result<()> { + let mut append = self.append.lock().map_err(storage)?; + if let Some(error) = &append.failure { + return Err(storage(format!( + "journal append is latched after failure: {error}" + ))); + } + if rows.is_empty() { + return Ok(()); + } + match append.append(rows) { + Ok(()) => { + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.status.durable = append.sequence; + self.shared.wake.notify_all(); + self.shared.progress.notify_waiters(); + Ok(()) + } + Err(error) => { + let message = error.to_string(); + append.failure = Some(message.clone()); + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.append_error = Some(message.clone()); + state.status.last_error = Some(message); + self.shared.progress.notify_waiters(); + Err(error) + } + } + } + + pub(crate) fn start(self: &Arc, writer: Arc>) -> Result<()> { + let mut worker = self.worker.lock().map_err(storage)?; + if worker.is_some() { + return Ok(()); + } + let cursor = { + let conn = writer.lock().map_err(storage)?; + match load_cursor(&conn, &self.identity)? { + Some(cursor) => cursor, + None => { + conn.execute( + "INSERT INTO _heron_journal_cursor VALUES (TRUE, ?, 0, 0, 0)", + duckdb::params![self.identity], + ) + .map_err(storage)?; + Cursor::default() + } + } + }; + let durable = self.status().durable; + if cursor.sequence > durable { + return Err(storage("journal cursor is ahead of durable records")); + } + self.shared.index_result(Ok(cursor.sequence)); + let shared = self.shared.clone(); + let directory = self.directory.clone(); + let identity = self.identity.clone(); + *worker = Some( + std::thread::Builder::new() + .name("heron-journal-index".into()) + .spawn(move || index_worker(directory, identity, writer, shared, cursor)) + .map_err(storage)?, + ); + Ok(()) + } + + pub(crate) async fn drain(&self) -> Result<()> { + let target = self.status().durable; + let deadline = tokio::time::Instant::now() + DRAIN_TIMEOUT; + loop { + let notified = self.shared.progress.notified(); + tokio::pin!(notified); + // Register before the state check, so a final progress wake cannot + // disappear between checking indexed and polling the future. + notified.as_mut().enable(); + { + let state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(error) = &state.append_error { + return Err(storage(format!( + "journal drain failed after append failure: {error}" + ))); + } + if state.status.indexed >= target { + return Ok(()); + } + } + if tokio::time::timeout_at(deadline, notified).await.is_err() { + let status = self.status(); + return Err(storage(format!( + "journal drain timed out: durable={target}, indexed={}, last_error={}", + status.indexed, + status + .last_error + .as_deref() + .unwrap_or("index worker has not advanced"), + ))); + } + } + } + + pub(crate) fn status(&self) -> Status { + self.shared + .state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .status + .clone() + } + + pub(crate) fn hydrate( + conn: &Connection, + table: Table, + id: &str, + ) -> Result> { + Self::hydrate_limited(conn, table, id, [u64::MAX; 4]) + } + + /// Service classification needs only small samples. Inspect persisted + /// lengths before touching payload bytes; oversized fields remain absent. + pub(crate) fn hydrate_sample( + conn: &Connection, + table: Table, + id: &str, + request_max: usize, + response_max: usize, + ) -> Result> { + Self::hydrate_limited( + conn, + table, + id, + [request_max as u64, response_max as u64, u64::MAX, u64::MAX], + ) + } + + fn hydrate_limited( + conn: &Connection, + table: Table, + id: &str, + limits: [u64; 4], + ) -> Result> { + let found = conn.query_row( + "SELECT fields, tokens_estimated FROM _heron_journal_payloads WHERE entity = ? AND id = ?", + duckdb::params![table.name(), id], + |row| Ok((row.get::<_, String>(0)?, row.get::<_, bool>(1)?)), + ); + let (fields, tokens_estimated) = match found { + Ok(found) => found, + Err(duckdb::Error::QueryReturnedNoRows) => return Ok(None), + Err(error) => return Err(storage(error)), + }; + let refs: Refs = serde_json::from_str(&fields).map_err(storage)?; + let database = conn + .path() + .ok_or_else(|| storage("journal payload references require an on-disk database"))?; + let mut path = database.as_os_str().to_os_string(); + path.push(".journal"); + let directory = PathBuf::from(path); + let journal_id = identity(&directory, false)?; + // A moved database and matching directory work; an unrelated directory + // must never be accepted just because its numeric offsets happen to fit. + load_cursor(conn, &journal_id)? + .ok_or_else(|| storage("journal payload has no bound cursor"))?; + let load = |reference: &Option, limit: u64| -> Result>> { + reference + .as_ref() + .filter(|reference| reference.length <= limit) + .map(|reference| read_payload(&directory, reference)) + .transpose() + }; + Ok(Some(PayloadFields { + request_body: load(&refs.request_body, limits[0])?, + response_body: load(&refs.response_body, limits[1])?, + request_headers: load(&refs.request_headers, limits[2])?, + response_headers: load(&refs.response_headers, limits[3])?, + tokens_estimated, + })) + } + + pub(crate) fn estimated(conn: &Connection, id: &str) -> Result> { + match conn.query_row( + "SELECT tokens_estimated FROM _heron_journal_payloads WHERE entity = 'spans' AND id = ?", + duckdb::params![id], |row| row.get(0), + ) { + Ok(value) => Ok(Some(value)), + Err(duckdb::Error::QueryReturnedNoRows) => Ok(None), + Err(error) => Err(storage(error)), + } + } +} + +impl Drop for Journal { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Release); + self.shared.wake.notify_all(); + if let Some(worker) = self + .worker + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + if worker.join().is_err() { + tracing::error!("journal index worker panicked during shutdown"); + } + } + } +} + +fn storage(error: impl std::fmt::Display) -> AppError { + AppError::Storage(format!("journal: {error}")) +} + +fn sync_directory(path: &Path) -> Result<()> { + File::open(path) + .and_then(|file| file.sync_all()) + .map_err(storage) +} + +fn segment_path(directory: &Path, prefix: &str, segment: u64) -> PathBuf { + directory.join(format!("{prefix}{segment:020}.jrn")) +} + +/// A directory scan stores only a count/max, not an in-memory backlog of paths. +fn last_segment(directory: &Path, prefix: &str) -> Result> { + let mut last = None; + let mut count = 0_u64; + for entry in fs::read_dir(directory).map_err(storage)? { + let entry = entry.map_err(storage)?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + let Some(number) = name.strip_prefix(prefix) else { + continue; + }; + let number = number + .strip_suffix(".jrn") + .ok_or_else(|| storage("invalid journal segment name"))?; + if number.len() != 20 || !number.bytes().all(|b| b.is_ascii_digit()) { + return Err(storage("invalid journal numeric segment")); + } + let segment: u64 = number.parse().map_err(storage)?; + count = count + .checked_add(1) + .ok_or_else(|| storage("too many journal segments"))?; + last = Some(last.map_or(segment, |old: u64| old.max(segment))); + } + if let Some(last) = last { + if last.checked_add(1) != Some(count) { + return Err(storage("missing journal segment")); + } + } + Ok(last) +} + +fn identity(directory: &Path, create: bool) -> Result { + let path = directory.join("identity"); + if create && !path.exists() { + let mut bytes = [0_u8; 68]; + bytes[..4].copy_from_slice(b"HJI1"); + File::open("/dev/urandom") + .and_then(|mut file| file.read_exact(&mut bytes[4..36])) + .map_err(storage)?; + let hash = Sha256::digest(&bytes[..36]); + bytes[36..].copy_from_slice(&hash); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .map_err(storage)?; + file.write_all(&bytes).map_err(storage)?; + file.sync_all().map_err(storage)?; + sync_directory(directory)?; + } + let bytes = fs::read(path).map_err(storage)?; + if bytes.len() != 68 + || &bytes[..4] != b"HJI1" + || Sha256::digest(&bytes[..36])[..] != bytes[36..] + { + return Err(storage("invalid journal identity")); + } + Ok(bytes[4..36] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) +} + +fn header(magic: [u8; 4], length: u64, sequence: u64, hash: [u8; 32]) -> [u8; HEADER_LEN] { + let mut bytes = [0_u8; HEADER_LEN]; + bytes[..4].copy_from_slice(&magic); + bytes[4..8].copy_from_slice(&1_u32.to_le_bytes()); + bytes[8..16].copy_from_slice(&length.to_le_bytes()); + bytes[16..24].copy_from_slice(&sequence.to_le_bytes()); + bytes[24..56].copy_from_slice(&hash); + let checksum = Sha256::digest(&bytes[..56]); + bytes[56..].copy_from_slice(&checksum); + bytes +} + +struct FrameHeader { + length: u64, + sequence: u64, + hash: [u8; 32], +} + +fn parse_header(bytes: &[u8; HEADER_LEN], magic: [u8; 4]) -> Result { + if bytes[..4] != magic + || bytes[4..8] != 1_u32.to_le_bytes() + || Sha256::digest(&bytes[..56])[..] != bytes[56..] + { + return Err(storage( + "journal frame header is corrupt or has unsupported version", + )); + } + Ok(FrameHeader { + length: u64::from_le_bytes(bytes[8..16].try_into().map_err(storage)?), + sequence: u64::from_le_bytes(bytes[16..24].try_into().map_err(storage)?), + hash: bytes[24..56].try_into().map_err(storage)?, + }) +} + +fn hash_bytes(file: &mut File, length: u64) -> Result<[u8; 32]> { + let mut hasher = Sha256::new(); + let mut remaining = length; + let mut buffer = [0_u8; 64 * 1024]; + while remaining > 0 { + let take = remaining.min(buffer.len() as u64) as usize; + file.read_exact(&mut buffer[..take]).map_err(storage)?; + hasher.update(&buffer[..take]); + remaining -= take as u64; + } + Ok(hasher.finalize().into()) +} + +/// Recovery validates complete frames; only an incomplete last-segment tail +/// may be truncated. Header checksums distinguish corrupted lengths from tears. +fn recover_segment( + directory: &Path, + prefix: &str, + segment: u64, + last: bool, + magic: [u8; 4], + mut visit: impl FnMut(FrameHeader, u64, &mut File) -> Result<()>, +) -> Result { + let mut file = OpenOptions::new() + .read(true) + .write(true) + .open(segment_path(directory, prefix, segment)) + .map_err(storage)?; + let length = file.metadata().map_err(storage)?.len(); + let mut offset = 0_u64; + while offset < length { + let remaining = length - offset; + if remaining < HEADER_LEN as u64 { + let mut partial = vec![0_u8; remaining as usize]; + file.seek(SeekFrom::Start(offset)).map_err(storage)?; + file.read_exact(&mut partial).map_err(storage)?; + let prefix_len = partial.len().min(4); + if !last + || partial[..prefix_len] != magic[..prefix_len] + || (partial.len() >= 8 && partial[4..8] != 1_u32.to_le_bytes()) + { + return Err(storage( + "incomplete/corrupt journal header before segment end", + )); + } + file.set_len(offset).map_err(storage)?; + file.sync_all().map_err(storage)?; + break; + } + file.seek(SeekFrom::Start(offset)).map_err(storage)?; + let mut bytes = [0_u8; HEADER_LEN]; + file.read_exact(&mut bytes).map_err(storage)?; + let frame = parse_header(&bytes, magic)?; + let end = offset + .checked_add(HEADER_LEN as u64) + .and_then(|v| v.checked_add(frame.length)) + .ok_or_else(|| storage("journal frame length overflow"))?; + if end > length { + if !last { + return Err(storage("incomplete frame in a non-final journal segment")); + } + file.set_len(offset).map_err(storage)?; + file.sync_all().map_err(storage)?; + break; + } + if hash_bytes(&mut file, frame.length)? != frame.hash { + return Err(storage("journal frame checksum mismatch")); + } + file.seek(SeekFrom::Start(offset + HEADER_LEN as u64)) + .map_err(storage)?; + visit(frame, offset, &mut file)?; + offset = end; + } + Ok(offset) +} + +fn remember( + dedup: &mut HashMap<[u8; 32], PayloadRef>, + order: &mut VecDeque<[u8; 32]>, + reference: PayloadRef, +) { + if dedup.contains_key(&reference.hash) { + return; + } + if dedup.len() >= DEDUP_ENTRIES { + if let Some(old) = order.pop_front() { + dedup.remove(&old); + } + } + order.push_back(reference.hash); + dedup.insert(reference.hash, reference); +} + +fn recover_payloads( + directory: &Path, +) -> Result<(u64, u64, HashMap<[u8; 32], PayloadRef>, VecDeque<[u8; 32]>)> { + let mut dedup = HashMap::new(); + let mut order = VecDeque::new(); + let Some(last) = last_segment(directory, "payload-")? else { + return Ok((0, 0, dedup, order)); + }; + let mut end = 0; + for segment in 0..=last { + end = recover_segment( + directory, + "payload-", + segment, + segment == last, + PAYLOAD_MAGIC, + |header, offset, _| { + if header.sequence != 0 { + return Err(storage("invalid payload sequence")); + } + remember( + &mut dedup, + &mut order, + PayloadRef { + segment, + offset: offset + HEADER_LEN as u64, + length: header.length, + hash: header.hash, + }, + ); + Ok(()) + }, + )?; + } + Ok((last, end, dedup, order)) +} + +fn recover_records(directory: &Path) -> Result<(u64, u64, u64)> { + let Some(last) = last_segment(directory, "records-")? else { + return Ok((0, 0, 0)); + }; + let mut sequence = 0_u64; + let mut end = 0; + for segment in 0..=last { + end = recover_segment( + directory, + "records-", + segment, + segment == last, + RECORD_MAGIC, + |header, _, file| { + if header.length > MAX_METADATA as u64 { + return Err(storage("journal metadata frame exceeds bound")); + } + let mut bytes = vec![0_u8; header.length as usize]; + file.read_exact(&mut bytes).map_err(storage)?; + let batch: Batch = serde_json::from_slice(&bytes).map_err(storage)?; + if sequence.checked_add(1) != Some(header.sequence) + || batch.sequence != header.sequence + { + return Err(storage("journal metadata sequence gap")); + } + for row in &batch.rows { + if let Some(refs) = &row.payloads { + for reference in refs.all().into_iter().flatten() { + payload_header(directory, reference)?; + } + } + } + sequence = header.sequence; + Ok(()) + }, + )?; + } + Ok((last, end, sequence)) +} + +fn payload_header(directory: &Path, reference: &PayloadRef) -> Result { + let mut file = + File::open(segment_path(directory, "payload-", reference.segment)).map_err(storage)?; + let offset = reference + .offset + .checked_sub(HEADER_LEN as u64) + .ok_or_else(|| storage("invalid payload reference offset"))?; + file.seek(SeekFrom::Start(offset)).map_err(storage)?; + let mut bytes = [0_u8; HEADER_LEN]; + file.read_exact(&mut bytes).map_err(storage)?; + let header = parse_header(&bytes, PAYLOAD_MAGIC)?; + let end = reference + .offset + .checked_add(reference.length) + .ok_or_else(|| storage("payload reference overflow"))?; + if header.length != reference.length + || header.hash != reference.hash + || header.sequence != 0 + || file.metadata().map_err(storage)?.len() < end + { + return Err(storage("payload reference does not match journal frame")); + } + Ok(file) +} + +fn read_payload(directory: &Path, reference: &PayloadRef) -> Result> { + let mut file = payload_header(directory, reference)?; + let length = usize::try_from(reference.length).map_err(storage)?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(length).map_err(storage)?; + bytes.resize(length, 0); + file.read_exact(&mut bytes).map_err(storage)?; + if Sha256::digest(&bytes)[..] != reference.hash { + return Err(storage("journal payload checksum mismatch")); + } + Ok(bytes) +} + +fn load_cursor(conn: &Connection, identity: &str) -> Result> { + match conn.query_row( + "SELECT journal_id, sequence, segment, byte_offset FROM _heron_journal_cursor WHERE singleton = TRUE", [], + |row| Ok((row.get::<_, String>(0)?, Cursor { + sequence: row.get(1)?, segment: row.get(2)?, offset: row.get(3)?, + })), + ) { + Ok((stored, cursor)) if stored == identity => Ok(Some(cursor)), + Ok(_) => Err(storage("database cursor belongs to a different journal directory")), + Err(duckdb::Error::QueryReturnedNoRows) => Ok(None), + Err(error) => Err(storage(error)), + } +} + +fn next_batch(directory: &Path, mut cursor: Cursor) -> Result<(Batch, Cursor)> { + loop { + let mut file = + File::open(segment_path(directory, "records-", cursor.segment)).map_err(storage)?; + if file.metadata().map_err(storage)?.len() == cursor.offset { + cursor.segment = cursor + .segment + .checked_add(1) + .ok_or_else(|| storage("journal segment overflow"))?; + cursor.offset = 0; + continue; + } + file.seek(SeekFrom::Start(cursor.offset)).map_err(storage)?; + let mut bytes = [0_u8; HEADER_LEN]; + file.read_exact(&mut bytes).map_err(storage)?; + let header = parse_header(&bytes, RECORD_MAGIC)?; + if header.length > MAX_METADATA as u64 { + return Err(storage("journal metadata frame exceeds bound")); + } + let mut bytes = vec![0_u8; header.length as usize]; + file.read_exact(&mut bytes).map_err(storage)?; + if Sha256::digest(&bytes)[..] != header.hash { + return Err(storage("journal metadata checksum mismatch")); + } + let batch: Batch = serde_json::from_slice(&bytes).map_err(storage)?; + if batch.sequence != header.sequence + || cursor.sequence.checked_add(1) != Some(batch.sequence) + { + return Err(storage("journal index cursor sequence gap")); + } + cursor.sequence = batch.sequence; + cursor.offset = cursor + .offset + .checked_add(HEADER_LEN as u64) + .and_then(|v| v.checked_add(header.length)) + .ok_or_else(|| storage("journal cursor overflow"))?; + return Ok((batch, cursor)); + } +} + +fn apply_batch( + conn: &mut Connection, + identity: &str, + batch: &Batch, + next: Cursor, +) -> Result { + let tx = conn.transaction().map_err(storage)?; + let current = + load_cursor(&tx, identity)?.ok_or_else(|| storage("journal cursor disappeared"))?; + if current.sequence >= batch.sequence { + return Ok(current); + } + if current.sequence.checked_add(1) != Some(batch.sequence) { + return Err(storage("journal transaction sequence gap")); + } + for table in [ + Table::Spans, + Table::Exchanges, + Table::Traces, + Table::Metrics, + Table::FinishMetrics, + ] { + if !batch.rows.iter().any(|row| row.table == table) { + continue; + } + let mut appender = tx.appender(table.name()).map_err(storage)?; + for row in batch.rows.iter().filter(|row| row.table == table) { + let values: Vec = row.cells.iter().map(Cell::sql_value).collect(); + appender + .append_row(duckdb::appender_params_from_iter(values.iter())) + .map_err(storage)?; + } + appender.flush().map_err(storage)?; + } + { + let mut statement = tx.prepare( + "INSERT INTO _heron_journal_payloads (entity, id, fields, tokens_estimated) VALUES (?, ?, ?, ?)", + ).map_err(storage)?; + for row in &batch.rows { + let Some(refs) = &row.payloads else { continue }; + let Some(Cell::Text(id)) = row.cells.first() else { + return Err(storage("journal payload row has no text id")); + }; + let fields = serde_json::to_string(refs).map_err(storage)?; + statement + .execute(duckdb::params![ + row.table.name(), + id, + fields, + row.tokens_estimated + ]) + .map_err(storage)?; + } + } + let changed = tx.execute( + "UPDATE _heron_journal_cursor SET sequence = ?, segment = ?, byte_offset = ? WHERE singleton = TRUE AND journal_id = ?", + duckdb::params![next.sequence, next.segment, next.offset, identity], + ).map_err(storage)?; + if changed != 1 { + return Err(storage( + "journal cursor update did not affect its bound singleton", + )); + } + tx.commit().map_err(storage)?; + Ok(next) +} + +fn index_worker( + directory: PathBuf, + identity: String, + writer: Arc>, + shared: Arc, + mut cursor: Cursor, +) { + let mut pending = None; + let mut backoff = Duration::from_millis(100); + while !shared.stop.load(Ordering::Acquire) { + let durable = shared + .state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .status + .durable; + if cursor.sequence >= durable { + shared.wait(Duration::from_millis(100)); + continue; + } + if pending.is_none() { + match next_batch(&directory, cursor) { + Ok(batch) => pending = Some(batch), + Err(error) => { + shared.index_result(Err(error.to_string())); + shared.wait(backoff); + backoff = (backoff * 2).min(Duration::from_secs(2)); + continue; + } + } + } + // Never block shutdown on somebody else's writer guard. The actual + // transaction runs on this one dedicated blocking thread, off Tokio. + let result = match writer.try_lock() { + Ok(mut conn) => { + let (batch, next) = pending.as_ref().expect("pending batch loaded"); + apply_batch(&mut conn, &identity, batch, *next) + } + Err(TryLockError::WouldBlock) => { + shared.wait(Duration::from_millis(20)); + continue; + } + Err(TryLockError::Poisoned(error)) => Err(storage(error)), + }; + match result { + Ok(next) => { + cursor = next; + pending = None; + backoff = Duration::from_millis(100); + shared.index_result(Ok(cursor.sequence)); + } + Err(error) => { + tracing::warn!(error = %error, sequence = cursor.sequence, "journal indexing failed; cursor retained for retry"); + shared.index_result(Err(error.to_string())); + shared.wait(backoff); + backoff = (backoff * 2).min(Duration::from_secs(2)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs::{self, OpenOptions}; + use std::io::{Read, Seek, SeekFrom, Write}; + use std::path::PathBuf; + use std::time::Duration; + + use duckdb::types::{TimeUnit, Value}; + use h_storage::StorageBackend; + + struct Fixture { + _temp: tempfile::TempDir, + path: PathBuf, + writer: Arc>, + reader: Connection, + } + + impl Fixture { + async fn new() -> Self { + let temp = tempfile::tempdir().unwrap(); + let db = temp.path().join("index.duckdb"); + let backend = crate::DuckDbBackend::open_configured(&h_common::config::DuckDbConfig { + path: db.to_string_lossy().into_owned(), + threads: Some(1), + memory_limit_mb: Some(128), + read_pool_size: Some(1), + ..Default::default() + }) + .unwrap(); + backend.init().await.unwrap(); + let writer = backend.write_spans_conn.clone(); + let reader = writer.lock().unwrap().try_clone().unwrap(); + init_schema(&reader).unwrap(); + let path = PathBuf::from(format!("{}.journal", db.display())); + Self { + _temp: temp, + path, + writer, + reader, + } + } + + fn open(&self) -> Arc { + Arc::new(Journal::open(&self.path).unwrap()) + } + } + + fn owned(table: Table, values: &[Value]) -> Row { + let params: Vec<&dyn ToSql> = values.iter().map(|v| v as &dyn ToSql).collect(); + row(table, ¶ms).unwrap() + } + + fn span(id: &str, request: Option<&str>, response: Option<&str>) -> Row { + let mut v = vec![Value::Null; 38]; + for (i, text) in [ + (0, id), + (1, "source"), + (2, "127.0.0.1"), + (4, "127.0.0.1"), + (9, "openai-chat"), + (10, "model"), + (11, "chat"), + (13, "/v1/chat/completions"), + (26, "[]"), + (27, "[]"), + (32, "[]"), + (37, "llm"), + ] { + v[i] = Value::from(text.to_string()); + } + for (i, number) in [ + (3, 1000_i64), + (5, 8000), + (14, 200), + (16, 7), + (17, 3), + (31, 0), + (33, 0), + ] { + v[i] = Value::from(number); + } + v[6] = Value::Timestamp(TimeUnit::Microsecond, 1_000_000); + v[12] = Value::from(false); + v[28] = Value::from(false); + v[23] = request + .map(|s| Value::from(s.to_string())) + .unwrap_or(Value::Null); + v[24] = response + .map(|s| Value::from(s.to_string())) + .unwrap_or(Value::Null); + owned(Table::Spans, &v) + } + + fn exchange(id: &str, request: Option<&[u8]>, response: Option<&[u8]>) -> Row { + let mut v = vec![Value::Null; 19]; + for (i, text) in [ + (0, id), + (1, "source"), + (2, "127.0.0.1"), + (4, "127.0.0.1"), + (6, "POST"), + (7, "/v1/chat/completions"), + (8, "[]"), + (11, "[]"), + ] { + v[i] = Value::from(text.to_string()); + } + for (i, number) in [(3, 1000_i64), (5, 8000), (10, 200), (14, 0), (15, 0)] { + v[i] = Value::from(number); + } + v[9] = request + .map(|b| Value::from(b.to_vec())) + .unwrap_or(Value::Null); + v[12] = response + .map(|b| Value::from(b.to_vec())) + .unwrap_or(Value::Null); + v[13] = Value::from(false); + v[16] = Value::Timestamp(TimeUnit::Microsecond, 1_000_000); + owned(Table::Exchanges, &v) + } + + fn trace(id: &str, metadata: &str) -> Row { + let mut v = vec![Value::Null; 30]; + for (i, text) in [ + (0, id), + (1, "source"), + (2, "session"), + (3, "openai-chat"), + (4, "generic"), + (5, "127.0.0.1"), + (6, "127.0.0.1"), + (11, "[]"), + (12, "[]"), + (18, "complete"), + (24, "[]"), + (25, metadata), + (26, "[]"), + (29, "[]"), + ] { + v[i] = Value::from(text.to_string()); + } + for i in [9, 10, 13, 14, 15, 16, 27] { + v[i] = Value::from(0_u64); + } + v[7] = Value::Timestamp(TimeUnit::Microsecond, 1_000_000); + v[8] = Value::Timestamp(TimeUnit::Microsecond, 2_000_000); + owned(Table::Traces, &v) + } + + fn finish(count: u64) -> Row { + owned( + Table::FinishMetrics, + &[ + Value::Timestamp(TimeUnit::Microsecond, 1_000_000), + Value::from("source".to_string()), + Value::from("1m".to_string()), + Value::from("openai-chat".to_string()), + Value::from("model".to_string()), + Value::from("127.0.0.1".to_string()), + Value::from("stop".to_string()), + Value::from(count), + ], + ) + } + + fn segments(path: &Path, prefix: &str) -> Vec { + let mut paths: Vec<_> = fs::read_dir(path) + .unwrap() + .map(|e| e.unwrap().path()) + .filter(|p| p.file_name().unwrap().to_string_lossy().starts_with(prefix)) + .collect(); + paths.sort(); + paths + } + + fn payload_bytes(path: &Path) -> u64 { + segments(path, "payload-") + .iter() + .map(|p| fs::metadata(p).unwrap().len()) + .sum() + } + + // Catches two producers obtaining independent append cursors in one directory. + #[test] + fn directory_is_exclusively_locked_until_drop() { + let temp = tempfile::tempdir().unwrap(); + let first = Journal::open(temp.path()).unwrap(); + assert!(Journal::open(temp.path()).is_err()); + drop(first); + assert!(Journal::open(temp.path()).is_ok()); + } + + // Catches serde_json silently rewriting non-finite SQL doubles to NULL. + #[test] + fn row_rejects_nonfinite_values() { + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(row(Table::Metrics, &[&value]).is_err()); + } + } + + // Catches accidentally accepting unversioned DuckDB-specific value families. + #[test] + fn row_rejects_unsupported_sql_values() { + let unsupported = Value::Interval { + months: 1, + days: 2, + nanos: 3, + }; + assert!(row(Table::Metrics, &[&unsupported]).is_err()); + } + + // Catches an append taking the index writer lock or eagerly indexing bodies. + #[tokio::test] + async fn durable_append_does_not_wait_for_database_lock() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + journal.start(fixture.writer.clone()).unwrap(); + let guard = fixture.writer.lock().unwrap(); + journal + .append(vec![span("one", Some("full request"), None)]) + .unwrap(); + assert!(journal.status().durable > journal.status().indexed); + drop(guard); + tokio::time::timeout(Duration::from_secs(5), journal.drain()) + .await + .unwrap() + .unwrap(); + let inline: Option = fixture + .reader + .query_row("SELECT request_body FROM spans WHERE id = 'one'", [], |r| { + r.get(0) + }) + .unwrap(); + assert!(inline.is_none()); + assert_eq!( + Journal::hydrate(&fixture.reader, Table::Spans, "one") + .unwrap() + .unwrap() + .request_body + .as_deref(), + Some(&b"full request"[..]) + ); + } + + // Catches conflating NULL, empty payload and arbitrary HTTP bytes. + #[tokio::test] + async fn null_empty_and_binary_payloads_survive_index_and_reopen() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + journal + .append(vec![ + exchange("binary", Some(&[]), Some(&[0, 255, 128, 1])), + span("null", None, Some("")), + ]) + .unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + drop(journal); + let http = Journal::hydrate(&fixture.reader, Table::Exchanges, "binary") + .unwrap() + .unwrap(); + assert_eq!(http.request_body, Some(vec![])); + assert_eq!(http.response_body, Some(vec![0, 255, 128, 1])); + assert_eq!(http.request_headers.as_deref(), Some(&b"[]"[..])); + let call = Journal::hydrate(&fixture.reader, Table::Spans, "null") + .unwrap() + .unwrap(); + assert_eq!(call.request_body, None); + assert_eq!(call.response_body, Some(vec![])); + let inline: (String, Option>) = fixture + .reader + .query_row( + "SELECT request_headers, response_body FROM http_exchanges WHERE id = 'binary'", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!(inline, ("[]".into(), None)); + } + + // Catches entity-specific dedup caches or full payload copies in metadata. + #[tokio::test] + async fn identical_body_is_stored_once_across_entities() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + let body = "same complete body ".repeat(1024); + journal + .append(vec![span("call", Some(&body), None)]) + .unwrap(); + let first = payload_bytes(&fixture.path); + journal + .append(vec![exchange("http", Some(body.as_bytes()), None)]) + .unwrap(); + assert_eq!(payload_bytes(&fixture.path), first); + for path in segments(&fixture.path, "records-") { + let bytes = fs::read(path).unwrap(); + assert!(!bytes.windows(body.len()).any(|w| w == body.as_bytes())); + } + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + assert_eq!( + Journal::hydrate(&fixture.reader, Table::Exchanges, "http") + .unwrap() + .unwrap() + .request_body + .as_deref(), + Some(body.as_bytes()) + ); + } + + // Catches discarding durable records when no worker was running at crash. + #[tokio::test] + async fn restart_replays_records_appended_before_worker_start() { + let fixture = Fixture::new().await; + { + let journal = fixture.open(); + journal + .append(vec![span("restart", Some("retained"), None)]) + .unwrap(); + } + let reopened = fixture.open(); + reopened.start(fixture.writer.clone()).unwrap(); + reopened.drain().await.unwrap(); + assert_eq!( + Journal::hydrate(&fixture.reader, Table::Spans, "restart") + .unwrap() + .unwrap() + .request_body + .as_deref(), + Some(&b"retained"[..]) + ); + } + + // Catches replaying committed metric deltas or treating dimensions as identity. + // @scenario DUCKDB-JOURNAL-001 integration + #[tokio::test] + async fn cursor_restart_does_not_duplicate_incremental_metrics() { + let fixture = Fixture::new().await; + { + let journal = fixture.open(); + journal.append(vec![finish(2), finish(3)]).unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + } + let reopened = fixture.open(); + reopened.start(fixture.writer.clone()).unwrap(); + reopened.append(vec![finish(7)]).unwrap(); + reopened.drain().await.unwrap(); + let actual: (i64, i64) = fixture + .reader + .query_row( + "SELECT COUNT(*), CAST(SUM(count) AS BIGINT) FROM llm_finish_metrics", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!(actual, (3, 12)); + assert_eq!(reopened.status().durable, reopened.status().indexed); + } + + // Catches treating a final incomplete frame as permanent journal corruption. + #[test] + fn restart_repairs_only_an_incomplete_final_metadata_frame() { + let temp = tempfile::tempdir().unwrap(); + let journal = Journal::open(temp.path()).unwrap(); + journal.append(vec![finish(2)]).unwrap(); + drop(journal); + let path = segments(temp.path(), "records-").pop().unwrap(); + let original = fs::metadata(&path).unwrap().len(); + OpenOptions::new() + .append(true) + .open(&path) + .unwrap() + .write_all(b"HR") + .unwrap(); + let reopened = Journal::open(temp.path()).unwrap(); + assert_eq!(fs::metadata(&path).unwrap().len(), original); + drop(reopened); + } + + // Catches checksum corruption being treated as a truncatable final record. + #[test] + fn restart_rejects_a_complete_frame_with_bad_hash() { + let temp = tempfile::tempdir().unwrap(); + let journal = Journal::open(temp.path()).unwrap(); + journal.append(vec![finish(2)]).unwrap(); + drop(journal); + let path = segments(temp.path(), "records-").pop().unwrap(); + let mut file = OpenOptions::new() + .read(true) + .write(true) + .open(path) + .unwrap(); + file.seek(SeekFrom::End(-1)).unwrap(); + let mut last = [0_u8]; + file.read_exact(&mut last).unwrap(); + file.seek(SeekFrom::End(-1)).unwrap(); + file.write_all(&[last[0] ^ 1]).unwrap(); + file.sync_all().unwrap(); + assert!(Journal::open(temp.path()).is_err()); + } + + // Catches a stored cursor being silently applied to a different journal. + #[tokio::test] + async fn cursor_is_bound_to_journal_identity() { + let fixture = Fixture::new().await; + { + let journal = fixture.open(); + journal.append(vec![finish(2)]).unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + } + let other = tempfile::tempdir().unwrap(); + let different = Arc::new(Journal::open(other.path()).unwrap()); + assert!(different.start(fixture.writer.clone()).is_err()); + } + + // Catches applying the usual small-batch target as a destructive row cap. + #[tokio::test] + async fn trace_larger_than_batch_target_retains_exact_metadata() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + let metadata = format!( + "{{\"large\":\"{}\"}}", + "retained-trace-value".repeat(32 * 1024) + ); + journal.append(vec![trace("large", &metadata)]).unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + let stored: String = fixture + .reader + .query_row( + "SELECT metadata FROM traces WHERE turn_id = 'large'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(stored, metadata); + } + + // Catches a successful index pass erasing an earlier terminal append error. + #[tokio::test] + async fn index_progress_preserves_append_failure_status() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + journal.append(vec![finish(2)]).unwrap(); + { + let mut append = journal.append.lock().unwrap(); + append.payload.file = File::open(segment_path(&fixture.path, "payload-", 0)).unwrap(); + } + assert!(journal + .append(vec![span("failure", Some("write denied"), None)]) + .is_err()); + let failure = journal.status().last_error; + journal.start(fixture.writer.clone()).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while journal.status().indexed < journal.status().durable { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + assert_eq!(journal.status().last_error, failure); + assert!(journal.drain().await.is_err()); + } + + // Catches resuming append after a failed write, which could make a torn + // frame become a middle-of-log corruption. A read-only descriptor gives a + // deterministic I/O failure without filling a disk or changing process limits. + #[test] + fn append_io_failure_latches_and_prevents_later_metadata() { + let temp = tempfile::tempdir().unwrap(); + let journal = Journal::open(temp.path()).unwrap(); + journal.append(vec![finish(2)]).unwrap(); + let metadata = segments(temp.path(), "records-").pop().unwrap(); + let length = fs::metadata(&metadata).unwrap().len(); + { + let mut append = journal.append.lock().unwrap(); + append.payload.file = File::open(segment_path(temp.path(), "payload-", 0)).unwrap(); + } + assert!(journal + .append(vec![span("failed", Some("cannot write"), None)]) + .is_err()); + assert!(journal.append(vec![finish(7)]).is_err()); + assert_eq!(fs::metadata(metadata).unwrap().len(), length); + assert!(journal.status().last_error.is_some()); + drop(journal); + assert!(Journal::open(temp.path()).is_ok()); + } + + // Catches accepting a torn frame before a later segment as a safe tail. + #[test] + fn restart_rejects_incomplete_frame_before_a_later_segment() { + let temp = tempfile::tempdir().unwrap(); + let journal = Journal::open(temp.path()).unwrap(); + journal.append(vec![finish(2)]).unwrap(); + { + let mut append = journal.append.lock().unwrap(); + append.records = SegmentWriter::new(temp.path(), "records-", 1, 0).unwrap(); + } + journal.append(vec![finish(3)]).unwrap(); + drop(journal); + let path = segment_path(temp.path(), "records-", 0); + let length = fs::metadata(&path).unwrap().len(); + OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .set_len(length - 1) + .unwrap(); + assert!(Journal::open(temp.path()).is_err()); + } + + // Catches advancing the cursor on an index error instead of retrying the + // same durable batch. Only synthetic tables are removed and restored. + // @scenario DUCKDB-JOURNAL-001 fault + #[tokio::test] + async fn index_failure_keeps_cursor_and_retries_without_metric_duplicates() { + let fixture = Fixture::new().await; + let create_sql: String = fixture + .reader + .query_row( + "SELECT sql FROM duckdb_tables() WHERE table_name = 'spans'", + [], + |r| r.get(0), + ) + .unwrap(); + fixture.reader.execute_batch("DROP TABLE spans").unwrap(); + let journal = fixture.open(); + journal + .append(vec![span("retry", Some("preserved"), None), finish(5)]) + .unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while journal.status().last_error.is_none() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + assert_eq!(journal.status().indexed, 0); + let count: i64 = fixture + .reader + .query_row("SELECT COUNT(*) FROM llm_finish_metrics", [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, 0); + fixture.reader.execute_batch(&create_sql).unwrap(); + tokio::time::timeout(Duration::from_secs(5), journal.drain()) + .await + .unwrap() + .unwrap(); + let actual: (i64, i64) = fixture + .reader + .query_row( + "SELECT COUNT(*), CAST(SUM(count) AS BIGINT) FROM llm_finish_metrics", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!(actual, (1, 5)); + assert_eq!( + Journal::hydrate(&fixture.reader, Table::Spans, "retry") + .unwrap() + .unwrap() + .request_body + .as_deref(), + Some(&b"preserved"[..]) + ); + } + + // Catches loading an oversized response just to discover it is not a + // service-classification sample. Only its small locator may be inspected. + #[tokio::test] + async fn sampling_skips_oversized_body_before_reading_payload_bytes() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + let body = "large body ".repeat(16 * 1024); + journal + .append(vec![span("sample", Some(&body), Some("small response"))]) + .unwrap(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + let reference = journal + .append + .lock() + .unwrap() + .dedup + .get(&<[u8; 32]>::from(Sha256::digest(body.as_bytes()))) + .unwrap() + .clone(); + let mut file = OpenOptions::new() + .write(true) + .open(segment_path(&fixture.path, "payload-", reference.segment)) + .unwrap(); + file.seek(SeekFrom::Start(reference.offset)).unwrap(); + file.write_all(b"!").unwrap(); + file.sync_all().unwrap(); + let sample = + Journal::hydrate_sample(&fixture.reader, Table::Spans, "sample", 32 * 1024, 8192) + .unwrap() + .unwrap(); + assert_eq!(sample.request_body, None); + assert_eq!( + sample.response_body.as_deref(), + Some(&b"small response"[..]) + ); + assert_eq!(sample.request_headers.as_deref(), Some(&b"[]"[..])); + assert!(Journal::hydrate(&fixture.reader, Table::Spans, "sample").is_err()); + } + + // Catches an auxiliary lookup fabricating payloads for legacy inline rows. + #[tokio::test] + async fn legacy_rows_without_refs_use_caller_fallback() { + let fixture = Fixture::new().await; + assert_eq!( + Journal::hydrate(&fixture.reader, Table::Spans, "legacy").unwrap(), + None + ); + assert_eq!(Journal::estimated(&fixture.reader, "legacy").unwrap(), None); + } + + #[tokio::test] + async fn payload_rotation_survives_restart_without_truncating_large_body() { + let fixture = Fixture::new().await; + let payload = vec![b'x'; SEGMENT_LIMIT as usize + 17]; + { + let journal = fixture.open(); + journal + .append(vec![exchange( + "oversized", + Some(&payload), + Some(b"small response"), + )]) + .unwrap(); + journal + .append(vec![exchange( + "after-rotation", + Some(b"following request"), + None, + )]) + .unwrap(); + assert!(last_segment(&fixture.path, "payload-").unwrap().unwrap() >= 1); + } + let journal = fixture.open(); + journal.start(fixture.writer.clone()).unwrap(); + journal.drain().await.unwrap(); + let first = Journal::hydrate(&fixture.reader, Table::Exchanges, "oversized") + .unwrap() + .unwrap(); + assert_eq!(first.request_body.as_deref(), Some(payload.as_slice())); + assert_eq!( + first.response_body.as_deref(), + Some(b"small response".as_slice()) + ); + let next = Journal::hydrate(&fixture.reader, Table::Exchanges, "after-rotation") + .unwrap() + .unwrap(); + assert_eq!( + next.request_body.as_deref(), + Some(b"following request".as_slice()) + ); + } + + #[tokio::test] + async fn committed_cursor_survives_restart_before_progress_publication() { + let fixture = Fixture::new().await; + let journal = fixture.open(); + journal.start(fixture.writer.clone()).unwrap(); + let mut conn = fixture.writer.lock().unwrap(); + journal.append(vec![finish(2)]).unwrap(); + let cursor = load_cursor(&conn, &journal.identity).unwrap().unwrap(); + let (batch, next) = next_batch(&fixture.path, cursor).unwrap(); + apply_batch(&mut conn, &journal.identity, &batch, next).unwrap(); + assert_eq!( + journal.status().indexed, + 0, + "simulate interruption after commit, before shared progress publication" + ); + drop(journal); + drop(conn); + let recovered = fixture.open(); + recovered.start(fixture.writer.clone()).unwrap(); + recovered.drain().await.unwrap(); + let count: u64 = fixture + .reader + .query_row( + "SELECT CAST(SUM(count) AS UBIGINT) FROM llm_finish_metrics", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!( + count, 2, + "already committed metric increments must not replay twice" + ); + assert_eq!(recovered.status().durable, recovered.status().indexed); + } +} diff --git a/server/h-storage-duckdb/src/journal_contract_tests.rs b/server/h-storage-duckdb/src/journal_contract_tests.rs new file mode 100644 index 00000000..93a57aab --- /dev/null +++ b/server/h-storage-duckdb/src/journal_contract_tests.rs @@ -0,0 +1,201 @@ +//! Behavioral gates for the optional durable journal ingestion path. +use crate::DuckDbBackend; +use h_common::config::DuckDbConfig; +use h_llm::model::{ApiType, LlmCall}; +use h_storage::StorageBackend; +use std::sync::Arc; +use std::time::Duration; + +fn call(id: &str) -> LlmCall { + LlmCall { + source_id: "synthetic".into(), + id: id.into(), + wire_api: "openai-chat", + model: "synthetic-model".into(), + api_type: ApiType::Chat, + request_time: 1_700_000_000_000_000, + response_time: Some(1_700_000_000_001_000), + complete_time: Some(1_700_000_000_002_000), + request_path: "/v1/chat/completions".into(), + is_stream: false, + request_body: Some("synthetic input 中文".repeat(65_536)), + status_code: Some(200), + finish_reason: Some("stop".into()), + response_body: Some( + r#"{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5}}"#.into(), + ), + input_tokens: Some(10), + output_tokens: Some(5), + total_tokens: Some(15), + cache_read_input_tokens: None, + cache_creation_input_tokens: None, + ttft_ms: Some(1.0), + e2e_latency_ms: Some(2.0), + client_ip: "127.0.0.1".parse().unwrap(), + client_port: 1000, + server_ip: "127.0.0.1".parse().unwrap(), + server_port: 8080, + response_id: Some("synthetic-response".into()), + request_headers: vec![ + ("x-synthetic".into(), "first".into()), + ("x-synthetic".into(), "second".into()), + ], + response_headers: vec![], + is_agent_request: false, + tool_surface: None, + agent_topology: None, + tool_call_count: 0, + tool_names: vec![], + body_bytes_dropped: 0, + process: None, + } +} +fn options(dir: &std::path::Path) -> DuckDbConfig { + serde_json::from_value(serde_json::json!({ + "path": dir.join("index.duckdb").to_str().unwrap(), + "threads": 1, "memory_limit_mb": 256, "read_pool_size": 1, "journal": true + })) + .unwrap() +} + +// @scenario DUCKDB-JOURNAL-001 integration +#[tokio::test] +async fn journal_keeps_large_payload_outside_database_and_preserves_detail() { + let dir = tempfile::tempdir().unwrap(); + let backend = DuckDbBackend::open_configured(&options(dir.path())).unwrap(); + backend.init().await.unwrap(); + let original = call("external-body"); + let expected = original.request_body.clone(); + backend.write_spans(vec![original]).await.unwrap(); + let mut found = false; + for _ in 0..200 { + if backend + .query_span_by_id("external-body") + .await + .unwrap() + .is_some() + { + found = true; + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(found, "durable record must eventually become queryable"); + let stored_bytes: Option = backend + .test_conn() + .lock() + .unwrap() + .query_row( + "SELECT length(request_body) FROM spans WHERE id = 'external-body'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!( + stored_bytes, None, + "full request payload must be external, not inline in DuckDB" + ); + let detail = backend + .query_span_by_id("external-body") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.request_body, expected); + assert_eq!(detail.finish_reason.as_deref(), Some("stop")); + assert_eq!(detail.tokens_estimated, false); + assert_eq!( + detail.request_headers.as_deref(), + Some(r#"[["x-synthetic","first"],["x-synthetic","second"]]"#) + ); +} + +// @scenario DUCKDB-JOURNAL-001 integration +#[tokio::test] +async fn journal_durable_ingestion_does_not_wait_for_database_writer() { + let dir = tempfile::tempdir().unwrap(); + let backend = Arc::new(DuckDbBackend::open_configured(&options(dir.path())).unwrap()); + backend.init().await.unwrap(); + let conn = backend.write_spans_conn.clone(); + let (ready_tx, ready_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let holder = std::thread::spawn(move || { + let _guard = conn.lock().unwrap(); + ready_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + ready_rx.recv().unwrap(); + let task_backend = backend.clone(); + let mut task = + tokio::spawn(async move { task_backend.write_spans(vec![call("paused-index")]).await }); + let acknowledged = tokio::time::timeout(Duration::from_millis(250), &mut task).await; + release_tx.send(()).unwrap(); + holder.join().unwrap(); + let completed_while_paused = acknowledged.is_ok(); + if let Ok(result) = acknowledged { + result.unwrap().unwrap(); + } else { + task.await.unwrap().unwrap(); + } + assert!( + completed_while_paused, + "durable ingestion must finish while indexing is paused" + ); +} + +#[tokio::test] +async fn journal_retention_cannot_be_bypassed_by_reopening_legacy_mode() { + let dir = tempfile::tempdir().unwrap(); + let mut options = options(dir.path()); + { + let backend = DuckDbBackend::open_configured(&options).unwrap(); + backend.init().await.unwrap(); + backend + .write_spans(vec![call("retained-payload")]) + .await + .unwrap(); + backend.flush_pending().await.unwrap(); + } + options.journal = false; + let backend = DuckDbBackend::open_configured(&options).unwrap(); + backend.init().await.unwrap(); + let result = backend + .apply_retention(h_storage::retention::RetentionPolicy { + spans_before: Some(std::time::SystemTime::now()), + ..Default::default() + }) + .await; + assert!( + result.is_err(), + "row retention must reject persistent journal ownership even when the mode is disabled" + ); + assert!(backend + .query_span_by_id("retained-payload") + .await + .unwrap() + .is_some()); +} + +#[tokio::test] +async fn journal_restart_does_not_backfill_metrics_behind_the_replay_cursor() { + let dir = tempfile::tempdir().unwrap(); + let options = options(dir.path()); + { + let backend = DuckDbBackend::open_configured(&options).unwrap(); + backend.init().await.unwrap(); + backend + .write_spans(vec![call("indexed-before-metrics")]) + .await + .unwrap(); + backend.flush_pending().await.unwrap(); + } + let backend = DuckDbBackend::open_configured(&options).unwrap(); + backend.init().await.unwrap(); + backend.flush_pending().await.unwrap(); + let count: u64 = backend + .test_conn() + .lock() + .unwrap() + .query_row("SELECT COUNT(*) FROM llm_metrics", [], |r| r.get(0)) + .unwrap(); + assert_eq!(count, 0, "journal metrics must replay only their original increments, not a second span-derived backfill"); +} diff --git a/server/h-storage-duckdb/src/journal_read_tests.rs b/server/h-storage-duckdb/src/journal_read_tests.rs new file mode 100644 index 00000000..c6c7d59b --- /dev/null +++ b/server/h-storage-duckdb/src/journal_read_tests.rs @@ -0,0 +1,505 @@ +//! Read-path compatibility gates for synthetic journal payloads. +use crate::DuckDbBackend; +use bytes::Bytes; +use h_common::config::DuckDbConfig; +use h_llm::model::{ApiType, LlmCall}; +use h_llm::wire_apis as wa; +use h_protocol::model::{HttpRequestData, HttpResponseData}; +use h_protocol::net::FlowKey; +use h_protocol::HttpExchange; +use h_storage::query::{ + DimensionFilter, ServicesQuery, ServicesTopologyQuery, SessionTracesQuery, SpansQuery, + TimeRange, +}; +use h_storage::StorageBackend; +use h_turn::{Trace, TraceStatus}; +use std::path::Path; +use std::sync::Arc; +use std::time::Duration; + +const TIME_US: i64 = 1_700_000_000_000_000; + +fn options(dir: &Path, journal: bool) -> DuckDbConfig { + // Compile against the pre-feature configuration: RED must be behavioral. + serde_json::from_value(serde_json::json!({ + "path": dir.join("read-index.duckdb"), "threads": 1, + "memory_limit_mb": 256, "read_pool_size": 2, "journal": journal + })) + .unwrap() +} + +fn call(id: &str) -> LlmCall { + LlmCall { + source_id: "synthetic".into(), + id: id.into(), + wire_api: wa::ANTHROPIC, + model: "synthetic-model".into(), + api_type: ApiType::Chat, + request_time: TIME_US, + response_time: Some(TIME_US + 1_000), + complete_time: Some(TIME_US + 2_000), + request_path: "/v1/messages".into(), + is_stream: false, + request_body: Some( + serde_json::json!({ + "model": "synthetic-model", + "messages": [{"role": "user", "content": "u".repeat(600)}] + }) + .to_string(), + ), + status_code: Some(200), + finish_reason: Some("end_turn".into()), + response_body: Some( + serde_json::json!({ + "content": [{"type": "text", "text": "a".repeat(600)}], + "usage": {"input_tokens": 7, "output_tokens": 3} + }) + .to_string(), + ), + input_tokens: Some(7), + output_tokens: Some(3), + total_tokens: Some(10), + cache_read_input_tokens: None, + cache_creation_input_tokens: None, + ttft_ms: Some(1.0), + e2e_latency_ms: Some(2.0), + client_ip: "127.0.0.1".parse().unwrap(), + client_port: 1234, + server_ip: "127.0.0.1".parse().unwrap(), + server_port: 8080, + response_id: Some("synthetic-response".into()), + request_headers: vec![ + ("x-synthetic".into(), "first".into()), + ("x-synthetic".into(), "second".into()), + ], + response_headers: vec![("x-litellm-test".into(), "synthetic".into())], + is_agent_request: true, + tool_surface: None, + agent_topology: None, + tool_call_count: 0, + tool_names: vec![], + body_bytes_dropped: 0, + process: None, + } +} + +fn trace(call_id: &str) -> Trace { + Trace { + source_id: "synthetic".into(), + turn_id: "synthetic-turn".into(), + session_id: "synthetic-session".into(), + wire_api: wa::ANTHROPIC.into(), + agent_kind: "claude-cli".into(), + client_ip: "127.0.0.1".parse().unwrap(), + server_ip: "127.0.0.1".parse().unwrap(), + start_time_us: TIME_US, + end_time_us: TIME_US + 2_000, + duration_ms: 2, + call_count: 1, + models_used: vec!["synthetic-model".into()], + subagents_used: vec![], + total_input_tokens: 7, + total_output_tokens: 3, + total_cache_read_input_tokens: 0, + total_cache_creation_input_tokens: 0, + total_cost_usd: None, + status: TraceStatus::Complete, + final_finish_reason: Some("end_turn".into()), + user_input_preview: Some("u".repeat(500) + "…"), + user_call_id: Some(call_id.into()), + final_answer_preview: Some("a".repeat(500) + "…"), + final_call_id: Some(call_id.into()), + span_ids: vec![call_id.into()], + metadata: serde_json::json!({}), + tool_surfaces: vec![], + tool_call_total: 0, + agent_topology: None, + suspicious_skills: vec![], + } +} + +fn exchange(id: &str, sse: bool) -> HttpExchange { + let client_ip = "127.0.0.1".parse().unwrap(); + let server_ip = "127.0.0.1".parse().unwrap(); + let request = Arc::new(HttpRequestData { + flow_key: FlowKey::new("synthetic".into(), client_ip, 1234, server_ip, 8080), + client_addr: (client_ip, 1234), + server_addr: (server_ip, 8080), + method: "POST".into(), + uri: "/synthetic".into(), + version: 1, + headers: vec![ + ("x-synthetic".into(), "first".into()), + ("x-synthetic".into(), "second".into()), + ], + body: Bytes::from_static(&[0xff, 0x00, 0x01]), + timestamp_us: TIME_US, + process: None, + }); + let response = Arc::new(HttpResponseData { + flow_key: request.flow_key.clone(), + client_addr: request.client_addr, + server_addr: request.server_addr, + status: 200, + version: 1, + headers: vec![( + "content-type".into(), + if sse { + "text/event-stream" + } else { + "application/octet-stream" + } + .into(), + )], + body: Bytes::from_static(&[0xfe, 0x00]), + first_byte_timestamp_us: TIME_US + 1_000, + complete_timestamp_us: TIME_US + 2_000, + process: None, + }); + HttpExchange { + id: id.into(), + request, + response, + sse_event_count: if sse { 3 } else { 0 }, + sse_data_bytes: if sse { 42 } else { 0 }, + } +} + +async fn wait_for_row(backend: &DuckDbBackend, table: &str, key: &str, id: &str) { + let sql = format!("SELECT count(*) FROM {table} WHERE {key} = ?"); + tokio::time::timeout(Duration::from_secs(2), async { + loop { + let count: u64 = backend + .test_conn() + .lock() + .unwrap() + .query_row(&sql, [id], |row| row.get(0)) + .unwrap(); + if count == 1 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .expect("synthetic journal record must become indexed within two seconds"); +} + +fn time_range() -> TimeRange { + TimeRange { + start_us: TIME_US - 1, + end_us: TIME_US + 1_000_000, + } +} +fn spans_query() -> SpansQuery { + SpansQuery { + time_range: time_range(), + filter: DimensionFilter::default(), + status_codes: vec![], + finish_reasons: vec![], + client_ips: vec![], + server_ports: vec![], + request_path_contains: None, + is_stream: None, + sort_by: "request_time".into(), + sort_order: "DESC".into(), + page: 1, + page_size: 10, + } +} +fn session_query() -> SessionTracesQuery { + SessionTracesQuery { + source_id: "synthetic".into(), + session_id: "synthetic-session".into(), + cursor: None, + page_size: 10, + } +} + +fn truncate_payload_segments(options: &DuckDbConfig) { + let root = std::path::PathBuf::from(format!("{}.journal", options.path)); + assert!( + root.is_dir(), + "journal=true must create a payload journal directory" + ); + let root = root.canonicalize().unwrap(); + let mut count = 0; + for entry in std::fs::read_dir(&root).unwrap() { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_file() + && entry.file_name().to_string_lossy().starts_with("payload-") + { + let path = entry.path().canonicalize().unwrap(); + assert!( + path.starts_with(&root), + "only truncate this synthetic test journal" + ); + std::fs::OpenOptions::new() + .write(true) + .open(path) + .unwrap() + .set_len(0) + .unwrap(); + count += 1; + } + } + assert!(count > 0, "journal must contain persisted payload segments"); +} + +#[tokio::test] +async fn journal_reads_full_span_trace_and_session_payloads() { + let dir = tempfile::tempdir().unwrap(); + let backend = DuckDbBackend::open_configured(&options(dir.path(), true)).unwrap(); + backend.init().await.unwrap(); + let original = call("external-call"); + backend.write_spans(vec![original.clone()]).await.unwrap(); + backend + .write_traces(vec![trace("external-call")]) + .await + .unwrap(); + wait_for_row(&backend, "spans", "id", "external-call").await; + wait_for_row(&backend, "traces", "turn_id", "synthetic-turn").await; + let external: bool = backend.test_conn().lock().unwrap().query_row( + "SELECT request_body IS NULL AND response_body IS NULL AND request_headers IS NULL AND response_headers IS NULL FROM spans WHERE id = 'external-call'", + [], |row| row.get(0), + ).unwrap(); + assert!( + external, + "journal mode must not retain inline body or header payloads" + ); + let detail = backend + .query_span_by_id("external-call") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.request_body, original.request_body); + assert_eq!(detail.response_body, original.response_body); + assert_eq!( + detail.request_headers.as_deref(), + Some(r#"[["x-synthetic","first"],["x-synthetic","second"]]"#) + ); + assert!(!detail.tokens_estimated); + let full = backend + .query_spans_by_ids(&["external-call".into()], true) + .await + .unwrap(); + assert_eq!(full[0].request_body, original.request_body); + assert_eq!( + full[0].response_headers.as_deref(), + Some(r#"[["x-litellm-test","synthetic"]]"#) + ); + let detail = backend + .query_trace_by_id("synthetic-turn") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.user_input, Some("u".repeat(600))); + assert_eq!(detail.final_answer, Some("a".repeat(600))); + let page = backend + .query_session_traces(&session_query()) + .await + .unwrap(); + assert_eq!(page.items[0].user_input, Some("u".repeat(600))); + assert_eq!(page.items[0].final_answer, Some("a".repeat(600))); +} + +#[tokio::test] +async fn journal_exchange_reads_preserve_binary_headers_and_sse_absence() { + let dir = tempfile::tempdir().unwrap(); + let backend = DuckDbBackend::open_configured(&options(dir.path(), true)).unwrap(); + backend.init().await.unwrap(); + backend + .write_exchanges(vec![exchange("binary", false), exchange("sse", true)]) + .await + .unwrap(); + wait_for_row(&backend, "http_exchanges", "id", "binary").await; + wait_for_row(&backend, "http_exchanges", "id", "sse").await; + let external: bool = backend.test_conn().lock().unwrap().query_row( + "SELECT request_body IS NULL AND response_body IS NULL AND request_headers = '[]' AND response_headers = '[]' FROM http_exchanges WHERE id = 'binary'", + [], |row| row.get(0), + ).unwrap(); + assert!(external, "exchange payload bytes must be external"); + let detail = backend + .query_http_exchange_by_id("binary") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.request_body.as_deref(), Some("[binary, 3 bytes]")); + assert_eq!(detail.response_body.as_deref(), Some("[binary, 2 bytes]")); + assert_eq!( + detail.request_headers, + r#"[["x-synthetic","first"],["x-synthetic","second"]]"# + ); + assert_eq!( + detail.response_headers, + r#"[["content-type","application/octet-stream"]]"# + ); + let detail = backend + .query_http_exchange_by_id("sse") + .await + .unwrap() + .unwrap(); + assert!(detail.is_sse); + assert!(detail.response_body.is_none()); + assert_eq!(detail.sse_event_count, 3); + assert_eq!(detail.sse_data_bytes, 42); +} + +#[tokio::test] +async fn journal_opt_in_keeps_legacy_inline_payloads_readable() { + let dir = tempfile::tempdir().unwrap(); + let original = call("legacy-call"); + { + let backend = DuckDbBackend::open_configured(&options(dir.path(), false)).unwrap(); + backend.init().await.unwrap(); + backend.write_spans(vec![original.clone()]).await.unwrap(); + backend + .write_exchanges(vec![exchange("legacy-exchange", false)]) + .await + .unwrap(); + } + let backend = DuckDbBackend::open_configured(&options(dir.path(), true)).unwrap(); + backend.init().await.unwrap(); + let detail = backend + .query_span_by_id("legacy-call") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.request_body, original.request_body); + assert_eq!(detail.response_body, original.response_body); + assert!(!detail.tokens_estimated); + assert_eq!( + detail.request_headers.as_deref(), + Some(r#"[["x-synthetic","first"],["x-synthetic","second"]]"#) + ); + let detail = backend + .query_http_exchange_by_id("legacy-exchange") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.request_body.as_deref(), Some("[binary, 3 bytes]")); + assert_eq!( + detail.response_headers, + r#"[["content-type","application/octet-stream"]]"# + ); +} + +#[tokio::test] +async fn journal_lite_and_span_list_need_no_payload_files() { + let dir = tempfile::tempdir().unwrap(); + let opts = options(dir.path(), true); + let backend = DuckDbBackend::open_configured(&opts).unwrap(); + backend.init().await.unwrap(); + let mut estimated = call("estimated"); + estimated.response_body = Some(r#"{"content":[]}"#.into()); + backend + .write_spans(vec![call("wire"), estimated]) + .await + .unwrap(); + let mut short = trace("wire"); + short.user_input_preview = Some("short user".into()); + short.final_answer_preview = Some("short assistant".into()); + backend.write_traces(vec![short]).await.unwrap(); + wait_for_row(&backend, "spans", "id", "wire").await; + wait_for_row(&backend, "spans", "id", "estimated").await; + wait_for_row(&backend, "traces", "turn_id", "synthetic-turn").await; + truncate_payload_segments(&opts); + let lite = backend + .query_trace_spans("synthetic-turn", false) + .await + .unwrap(); + assert_eq!(lite.len(), 1); + assert!(lite[0].request_body.is_none()); + assert!(lite[0].response_body.is_none()); + assert!(lite[0].request_headers.is_none()); + assert!(lite[0].response_headers.is_none()); + let page = backend.query_spans(&spans_query()).await.unwrap(); + assert_eq!(page.total, 2); + assert!( + !page + .items + .iter() + .find(|item| item.id == "wire") + .unwrap() + .tokens_estimated + ); + assert!( + page.items + .iter() + .find(|item| item.id == "estimated") + .unwrap() + .tokens_estimated + ); + let detail = backend + .query_trace_by_id("synthetic-turn") + .await + .unwrap() + .unwrap(); + assert_eq!(detail.user_input.as_deref(), Some("short user")); + assert_eq!(detail.final_answer.as_deref(), Some("short assistant")); +} + +#[tokio::test] +async fn journal_payload_loss_propagates_through_detail_and_text_extraction() { + let dir = tempfile::tempdir().unwrap(); + let opts = options(dir.path(), true); + let backend = DuckDbBackend::open_configured(&opts).unwrap(); + backend.init().await.unwrap(); + backend.write_spans(vec![call("lost")]).await.unwrap(); + backend + .write_exchanges(vec![exchange("lost-exchange", false)]) + .await + .unwrap(); + backend.write_traces(vec![trace("lost")]).await.unwrap(); + wait_for_row(&backend, "spans", "id", "lost").await; + wait_for_row(&backend, "http_exchanges", "id", "lost-exchange").await; + wait_for_row(&backend, "traces", "turn_id", "synthetic-turn").await; + truncate_payload_segments(&opts); + assert!( + backend.query_span_by_id("lost").await.is_err(), + "payload loss must not look like an empty span body" + ); + assert!(backend + .query_spans_by_ids(&["lost".into()], true) + .await + .is_err()); + assert!(backend + .query_http_exchange_by_id("lost-exchange") + .await + .is_err()); + assert!( + backend.query_trace_by_id("synthetic-turn").await.is_err(), + "truncated previews must not hide payload read errors" + ); + assert!(backend + .query_session_traces(&session_query()) + .await + .is_err()); +} + +#[tokio::test] +async fn journal_service_samples_read_external_headers_and_propagate_loss() { + let dir = tempfile::tempdir().unwrap(); + let opts = options(dir.path(), true); + let backend = DuckDbBackend::open_configured(&opts).unwrap(); + backend.init().await.unwrap(); + backend.write_spans(vec![call("sample")]).await.unwrap(); + wait_for_row(&backend, "spans", "id", "sample").await; + let query = ServicesQuery { + time_range: time_range(), + sort_by: "call_count".into(), + sort_order: "DESC".into(), + limit: 10, + }; + let services = backend.query_services(&query).await.unwrap(); + assert_eq!(services.len(), 1); + assert_eq!(services[0].app.as_deref(), Some("litellm")); + truncate_payload_segments(&opts); + assert!(backend.query_services(&query).await.is_err()); + assert!(backend + .query_services_topology(&ServicesTopologyQuery { + time_range: time_range() + }) + .await + .is_err()); +} diff --git a/server/h-storage-duckdb/src/lib.rs b/server/h-storage-duckdb/src/lib.rs index 8bd24b3d..43349f2e 100644 --- a/server/h-storage-duckdb/src/lib.rs +++ b/server/h-storage-duckdb/src/lib.rs @@ -6,6 +6,11 @@ mod distincts; mod exchanges; #[cfg(feature = "fault-injection")] pub mod fault_injection; +mod journal; +#[cfg(test)] +mod journal_contract_tests; +#[cfg(test)] +mod journal_read_tests; mod metrics; mod pool; mod retention; @@ -18,12 +23,12 @@ use std::sync::{Arc, Mutex as StdMutex}; use async_trait::async_trait; use duckdb::Connection; -use tracing::info; use h_common::error::{AppError, Result}; use h_llm::model::LlmCall; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_protocol::HttpExchange; -use h_turn::{Trace, PairCandidate}; +use h_turn::{PairCandidate, Trace}; +use tracing::info; use h_storage::query::*; use h_storage::retention::{RetentionPolicy, RetentionReport}; @@ -58,6 +63,8 @@ pub struct DuckDbBackend { /// Captured at construction; used by `reopen_all_connections` to /// rebuild the reader pool at the same size. pub(crate) read_pool_size: usize, + connection_config: h_common::config::DuckDbConfig, + pub(crate) journal: Option>, /// Per-backend armed-fault set. Only present when the /// `fault-injection` feature is enabled; shared by reference with /// `read_pool` so writer-path and reader-path injections both see @@ -73,6 +80,21 @@ impl DuckDbBackend { } pub fn open_with_pool(path: &str, read_pool_size: usize) -> Result { + Self::open_configured(&h_common::config::DuckDbConfig { + path: path.to_string(), + read_pool_size: Some(read_pool_size.max(1)), + ..Default::default() + }) + } + + pub fn open_configured(options: &h_common::config::DuckDbConfig) -> Result { + let path = options.path.as_str(); + let read_pool_size = options.read_pool_size.unwrap_or(DEFAULT_READ_POOL_SIZE); + if options.threads == Some(0) || options.memory_limit_mb == Some(0) || read_pool_size == 0 { + return Err(AppError::Storage( + "duckdb resource limits must be positive".into(), + )); + } if let Some(parent) = std::path::Path::new(path).parent() { if !parent.as_os_str().is_empty() && !parent.exists() { std::fs::create_dir_all(parent).map_err(|e| { @@ -83,8 +105,21 @@ impl DuckDbBackend { })?; } } - let calls_writer = Connection::open(path) - .map_err(|e| AppError::Storage(format!("failed to open duckdb: {e}")))?; + let journal = if options.journal { + if path == ":memory:" || path.is_empty() { + return Err(AppError::Config( + "journal mode requires an on-disk DuckDB path".into(), + )); + } + let mut dir = std::path::PathBuf::from(path).into_os_string(); + dir.push(".journal"); + Some(Arc::new(journal::Journal::open(std::path::Path::new( + &dir, + ))?)) + } else { + None + }; + let calls_writer = Self::configured_connection(path, options)?; let turns_writer = calls_writer .try_clone() .map_err(|e| AppError::Storage(format!("failed to clone turns writer: {e}")))?; @@ -124,11 +159,41 @@ impl DuckDbBackend { ), db_path: path.to_string(), read_pool_size: pool_size, + connection_config: options.clone(), + journal, #[cfg(feature = "fault-injection")] fault_set, }) } + fn configured_connection( + path: &str, + options: &h_common::config::DuckDbConfig, + ) -> Result { + let mut config = duckdb::Config::default(); + if let Some(threads) = options.threads { + config = config + .threads(i64::try_from(threads).map_err(|_| { + AppError::Storage("duckdb threads exceed supported range".into()) + })?) + .map_err(|e| AppError::Storage(format!("invalid duckdb threads: {e}")))?; + } + if let Some(megabytes) = options.memory_limit_mb { + config = config + .max_memory(&format!("{megabytes}MB")) + .map_err(|e| AppError::Storage(format!("invalid duckdb memory limit: {e}")))?; + } + if let Some(enabled) = options.allocator_background_threads { + config = config + .with("allocator_background_threads", enabled.to_string()) + .map_err(|e| { + AppError::Storage(format!("invalid duckdb allocator background setting: {e}")) + })?; + } + Connection::open_with_flags(path, config) + .map_err(|e| AppError::Storage(format!("failed to open duckdb: {e}"))) + } + /// Test-only accessor for the per-backend fault-injection set. #[cfg(feature = "fault-injection")] pub fn fault_set(&self) -> &fault_injection::FaultSet { @@ -144,7 +209,45 @@ impl DuckDbBackend { #[async_trait] impl StorageBackend for DuckDbBackend { async fn init(&self) -> Result<()> { - schema::init(self).await + schema::init(self).await?; + let writer = self.write_spans_conn.clone(); + tokio::task::spawn_blocking(move || { + let conn = writer + .lock() + .map_err(|e| AppError::Storage(format!("lock journal schema writer: {e}")))?; + journal::init_schema(&conn) + }) + .await + .map_err(|e| AppError::Storage(format!("journal schema task failed: {e}")))??; + if let Some(journal) = &self.journal { + journal.start(self.write_spans_conn.clone())?; + } + Ok(()) + } + + fn durable_ingestion(&self) -> bool { + self.journal.is_some() + } + + async fn flush_pending(&self) -> Result<()> { + if let Some(journal) = &self.journal { + journal.drain().await?; + let status = journal.status(); + tracing::info!( + durable = status.durable, + indexed = status.indexed, + "journal index drained" + ); + } + Ok(()) + } + + async fn write_metric_batch( + &self, + wide: Vec, + finish: Vec, + ) -> Result<()> { + self.write_journal_metric_batch(wide, finish).await } async fn write_spans(&self, calls: Vec) -> Result<()> { @@ -316,12 +419,28 @@ impl StorageBackend for DuckDbBackend { } async fn checkpoint_traces_writer(&self) -> Result<()> { - let conn = self.write_traces_conn.clone(); + let calls = self.write_spans_conn.clone(); + let turns = self.write_traces_conn.clone(); + let metrics = self.write_metrics_conn.clone(); + let exchanges = self.write_exchanges_conn.clone(); tokio::task::spawn_blocking(move || { - let conn = conn + // A database-wide checkpoint needs a gap across all four writers. + // Each write batch holds just its own guard through commit/drop. + // Keep this lock order consistent with connection replacement. + let _calls_guard = calls + .lock() + .map_err(|e| AppError::Storage(format!("lock calls writer: {e}")))?; + let turns = turns .lock() .map_err(|e| AppError::Storage(format!("lock turns writer: {e}")))?; - conn.execute_batch("CHECKPOINT") + let _metrics_guard = metrics + .lock() + .map_err(|e| AppError::Storage(format!("lock metrics writer: {e}")))?; + let _exchanges_guard = exchanges + .lock() + .map_err(|e| AppError::Storage(format!("lock exchanges writer: {e}")))?; + turns + .execute_batch("CHECKPOINT") .map_err(|e| AppError::Storage(format!("CHECKPOINT failed: {e}")))?; Ok(()) }) @@ -332,6 +451,7 @@ impl StorageBackend for DuckDbBackend { async fn reopen_all_connections(&self) -> Result<()> { let path = self.db_path.clone(); let pool_size = self.read_pool_size; + let connection_config = self.connection_config.clone(); let calls_arc = self.write_spans_conn.clone(); let turns_arc = self.write_traces_conn.clone(); let metrics_arc = self.write_metrics_conn.clone(); @@ -341,8 +461,7 @@ impl StorageBackend for DuckDbBackend { // Open one fresh anchor connection to the on-disk file. // If the file itself is unreachable we surface the error // and the sweeper will retry on the next interval. - let anchor = Connection::open(&path) - .map_err(|e| AppError::Storage(format!("reopen duckdb anchor: {e}")))?; + let anchor = Self::configured_connection(&path, &connection_config)?; let turns_fresh = anchor .try_clone() .map_err(|e| AppError::Storage(format!("clone turns writer: {e}")))?; @@ -400,3 +519,117 @@ impl StorageBackend for DuckDbBackend { .map_err(|e| AppError::Storage(format!("spawn_blocking failed: {e}")))? } } + +#[cfg(test)] +mod resource_tests { + use super::*; + use h_common::config::DuckDbConfig; + + // @scenario DUCKDB-RESOURCES-001 unit + #[test] + fn configured_connection_forwards_allocator_background_threads() { + for enabled in [true, false] { + let cfg: DuckDbConfig = serde_json::from_value(serde_json::json!({ + "path": ":memory:", + "threads": 1, + "read_pool_size": 1, + "allocator_background_threads": enabled, + })) + .unwrap(); + let backend = DuckDbBackend::open_configured(&cfg).unwrap(); + let conn = backend.write_spans_conn.lock().unwrap(); + let actual: bool = conn + .query_row( + "SELECT current_setting('allocator_background_threads')", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!( + actual, enabled, + "allocator option must reach the database instance" + ); + } + } + + // @scenario DUCKDB-RESOURCES-001 unit + #[test] + fn configured_connection_honors_threads_and_memory_limit() { + let cfg = DuckDbConfig { + path: ":memory:".into(), + threads: Some(1), + memory_limit_mb: Some(256), + read_pool_size: Some(1), + ..DuckDbConfig::default() + }; + let backend = DuckDbBackend::open_configured(&cfg).unwrap(); + let conn = backend.write_spans_conn.lock().unwrap(); + let threads: i64 = conn + .query_row("SELECT current_setting('threads')", [], |r| r.get(0)) + .unwrap(); + let budget: String = conn + .query_row("SELECT current_setting('memory_limit')", [], |r| r.get(0)) + .unwrap(); + assert_eq!(threads, 1); + assert_eq!(budget, "244.1 MiB"); + assert_eq!(backend.read_pool_size, 1); + } + + // @scenario DUCKDB-RESOURCES-001 unit + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn checkpoint_waits_for_active_writer_without_losing_commit() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("checkpoint.duckdb"); + let options = DuckDbConfig { + path: path.to_string_lossy().into_owned(), + threads: Some(1), + memory_limit_mb: Some(256), + read_pool_size: Some(1), + ..DuckDbConfig::default() + }; + let backend = Arc::new(DuckDbBackend::open_configured(&options).unwrap()); + let (started_tx, started_rx) = tokio::sync::oneshot::channel(); + let (commit_tx, commit_rx) = std::sync::mpsc::channel(); + let writer_backend = backend.clone(); + let writer = std::thread::spawn(move || { + // Match production: a writer holds its guard until commit/drop. + let writer = writer_backend.write_spans_conn.lock().unwrap(); + writer + .execute_batch( + "CREATE TABLE checkpoint_fixture (value INTEGER);\ + INSERT INTO checkpoint_fixture VALUES (42);\ + BEGIN TRANSACTION; UPDATE checkpoint_fixture SET value = 43;", + ) + .unwrap(); + started_tx.send(()).unwrap(); + commit_rx + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap(); + writer.execute_batch("COMMIT").unwrap(); + }); + started_rx.await.unwrap(); + let checkpoint_backend = backend.clone(); + let mut checkpoint = + tokio::spawn(async move { checkpoint_backend.checkpoint_traces_writer().await }); + let early = + tokio::time::timeout(std::time::Duration::from_millis(150), &mut checkpoint).await; + // Always finish the writer, including on an unexpected early result. + commit_tx.send(()).unwrap(); + writer.join().unwrap(); + assert!( + early.is_err(), + "checkpoint must wait for an active writer, got {early:?}" + ); + checkpoint.await.unwrap().unwrap(); + let actual: i64 = backend + .write_spans_conn + .lock() + .unwrap() + .query_row("SELECT value FROM checkpoint_fixture", [], |r| r.get(0)) + .unwrap(); + assert_eq!( + actual, 43, + "checkpoint must preserve the committed writer row" + ); + } +} diff --git a/server/h-storage-duckdb/src/metrics.rs b/server/h-storage-duckdb/src/metrics.rs index 28a3d18a..48beed40 100644 --- a/server/h-storage-duckdb/src/metrics.rs +++ b/server/h-storage-duckdb/src/metrics.rs @@ -7,9 +7,10 @@ use h_common::error::{AppError, Result}; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_storage::query::*; +use crate::journal::{Journal, Table}; use crate::util::{ build_dimension_where, build_dimension_where_for_group, escape_standard, - parse_json_string_list, sql_in_list, us_to_timestamp, + parse_json_string_list, payload_utf8, sql_in_list, us_to_timestamp, }; use crate::DuckDbBackend; @@ -214,7 +215,104 @@ const SUM_FIELDS: &[&str] = &[ /// rows under a grouped query). const MAX_FIELDS: &[&str] = &["active_calls_max"]; +impl PreparedMetric { + fn parameters(&self) -> Vec<&dyn duckdb::ToSql> { + let p = self; + let m = &p.inner; + vec![ + &p.timestamp, + &p.source_id, + &p.granularity, + &p.wire_api, + &p.model, + &p.server_ip, + &m.call_count, + &m.stream_count, + &m.non_stream_count, + &m.active_calls_sum, + &m.active_calls_sample_count, + &m.active_calls_max, + &m.total_input_tokens, + &m.input_token_count, + &m.total_output_tokens, + &m.output_token_count, + &m.total_cache_read_input_tokens, + &m.total_cache_creation_input_tokens, + &m.error_count, + &m.error_4xx_count, + &m.error_429_count, + &m.error_5xx_count, + &m.ttft_sum, + &m.ttft_count, + &m.ttft_p50, + &m.ttft_p95, + &m.ttft_p99, + &m.ttft_stream_sum, + &m.ttft_stream_count, + &m.ttft_stream_p50, + &m.ttft_stream_p95, + &m.ttft_stream_p99, + &m.ttft_nonstream_sum, + &m.ttft_nonstream_count, + &m.ttft_nonstream_p50, + &m.ttft_nonstream_p95, + &m.ttft_nonstream_p99, + &m.e2e_sum, + &m.e2e_count, + &m.e2e_p50, + &m.e2e_p95, + &m.e2e_p99, + &m.tpot_sum, + &m.tpot_count, + &m.tpot_p50, + &m.tpot_p95, + &m.tpot_p99, + &m.tool_surface, + ] + } +} + +fn finish_parameters<'a>(ts: &'a Value, m: &'a LlmFinishMetric) -> Vec<&'a dyn duckdb::ToSql> { + vec![ + ts, + &m.source_id, + &m.granularity, + &m.wire_api, + &m.model, + &m.server_ip, + &m.finish_reason, + &m.count, + ] +} + impl DuckDbBackend { + pub(crate) async fn write_journal_metric_batch( + &self, + wide: Vec, + finish: Vec, + ) -> Result<()> { + let Some(journal) = self.journal.clone() else { + self.write_metrics(wide).await?; + return self.write_finish_metrics(finish).await; + }; + tokio::task::spawn_blocking(move || { + let prepared: Vec<_> = wide.into_iter().map(prepare_metric).collect(); + let mut rows = prepared + .iter() + .map(|p| crate::journal::row(crate::journal::Table::Metrics, &p.parameters())) + .collect::>>()?; + for m in finish { + let ts = Value::Timestamp(TimeUnit::Microsecond, m.timestamp_us); + rows.push(crate::journal::row( + crate::journal::Table::FinishMetrics, + &finish_parameters(&ts, &m), + )?); + } + journal.append(rows) + }) + .await + .map_err(|e| AppError::Storage(format!("journal metrics task failed: {e}")))? + } pub(crate) async fn write_metrics(&self, metrics: Vec) -> Result<()> { if metrics.is_empty() { return Ok(()); @@ -230,9 +328,18 @@ impl DuckDbBackend { } } let conn = self.write_metrics_conn.clone(); + let journal = self.journal.clone(); tokio::task::spawn_blocking(move || { let prepared: Vec = metrics.into_iter().map(prepare_metric).collect(); + if let Some(journal) = journal { + let rows = prepared + .iter() + .map(|p| crate::journal::row(crate::journal::Table::Metrics, &p.parameters())) + .collect::>>()?; + return journal.append(rows); + } + let conn = conn .lock() .map_err(|e| AppError::Storage(format!("failed to lock writer: {e}")))?; @@ -240,58 +347,8 @@ impl DuckDbBackend { .appender("llm_metrics") .map_err(|e| AppError::Storage(format!("failed to create appender: {e}")))?; for p in &prepared { - let m = &p.inner; appender - .append_row(duckdb::params![ - p.timestamp, - p.source_id, - p.granularity, - p.wire_api, - p.model, - p.server_ip, - m.call_count, - m.stream_count, - m.non_stream_count, - m.active_calls_sum, - m.active_calls_sample_count, - m.active_calls_max, - m.total_input_tokens, - m.input_token_count, - m.total_output_tokens, - m.output_token_count, - m.total_cache_read_input_tokens, - m.total_cache_creation_input_tokens, - m.error_count, - m.error_4xx_count, - m.error_429_count, - m.error_5xx_count, - m.ttft_sum, - m.ttft_count, - m.ttft_p50, - m.ttft_p95, - m.ttft_p99, - m.ttft_stream_sum, - m.ttft_stream_count, - m.ttft_stream_p50, - m.ttft_stream_p95, - m.ttft_stream_p99, - m.ttft_nonstream_sum, - m.ttft_nonstream_count, - m.ttft_nonstream_p50, - m.ttft_nonstream_p95, - m.ttft_nonstream_p99, - m.e2e_sum, - m.e2e_count, - m.e2e_p50, - m.e2e_p95, - m.e2e_p99, - m.tpot_sum, - m.tpot_count, - m.tpot_p50, - m.tpot_p95, - m.tpot_p99, - m.tool_surface.as_deref(), - ]) + .append_row(p.parameters().as_slice()) .map_err(|e| AppError::Storage(format!("failed to append metric: {e}")))?; } appender @@ -322,6 +379,7 @@ impl DuckDbBackend { // — they always come in pairs from the bucket finalizer and writing // them on the same connection avoids cross-table interleaving. let conn = self.write_metrics_conn.clone(); + let journal = self.journal.clone(); tokio::task::spawn_blocking(move || { // Pre-format the timestamp Value outside the writer lock, same // pattern as `prepare_metric`. @@ -330,6 +388,19 @@ impl DuckDbBackend { .map(|m| (Value::Timestamp(TimeUnit::Microsecond, m.timestamp_us), m)) .collect(); + if let Some(journal) = journal { + let rows = prepared + .iter() + .map(|(ts, m)| { + crate::journal::row( + crate::journal::Table::FinishMetrics, + &finish_parameters(ts, m), + ) + }) + .collect::>>()?; + return journal.append(rows); + } + let conn = conn .lock() .map_err(|e| AppError::Storage(format!("failed to lock writer: {e}")))?; @@ -338,16 +409,7 @@ impl DuckDbBackend { })?; for (ts, m) in &prepared { appender - .append_row(duckdb::params![ - ts, - m.source_id, - m.granularity, - m.wire_api, - m.model, - m.server_ip, - m.finish_reason, - m.count, - ]) + .append_row(finish_parameters(ts, m).as_slice()) .map_err(|e| { AppError::Storage(format!("failed to append finish metric: {e}")) })?; @@ -383,7 +445,8 @@ impl DuckDbBackend { let fields_sql = field_exprs.join(", "); let rows = if let Some(ref group_by) = query.group_by { // Grouped query: aggregate across the group dimension plus source_id. - let dim_where = build_dimension_where_for_group(&query.filter, group_by, escape_standard); + let dim_where = + build_dimension_where_for_group(&query.filter, group_by, escape_standard); let sql = format!( "SELECT epoch(timestamp) AS ts, {group_by}, {fields_sql} \ FROM llm_metrics \ @@ -582,7 +645,8 @@ impl DuckDbBackend { let limit = query.limit; // Per-(wire_api, model) breakdown shares the grouped-tier logic: // both dimensions are always specific, server_ip follows filter. - let dim_where = build_dimension_where_for_group(&query.filter, "wire_api", escape_standard); + let dim_where = + build_dimension_where_for_group(&query.filter, "wire_api", escape_standard); let gran = metrics_granularity_for_range(&query.time_range); let sql = format!( @@ -925,18 +989,19 @@ impl DuckDbBackend { // endpoint. We filter for shape (`headers LIKE '[%'`, // `body LIKE '{%'`) in Rust below. let body_sql = "SELECT server_ip, server_port, - response_headers, request_headers, request_body, response_body + response_headers, request_headers, request_body, response_body, id FROM ( - SELECT server_ip, server_port, + SELECT server_ip, server_port, id, response_headers, request_headers, request_body, response_body, ROW_NUMBER() OVER ( PARTITION BY server_ip, server_port - ORDER BY request_time DESC + ORDER BY request_time DESC, id ASC ) AS rn FROM spans WHERE request_time >= ? AND request_time < ? - ) WHERE rn <= 5"; + ) WHERE rn <= 5 + ORDER BY server_ip, server_port, rn, id"; let mut stmt = conn .prepare(body_sql) @@ -954,18 +1019,27 @@ impl DuckDbBackend { let server_port: u16 = row .get(1) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; - let resp_h: Option = row + let mut resp_h: Option = row .get(2) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; - let req_h: Option = row + let mut req_h: Option = row .get(3) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; - let req_b: Option = row + let mut req_b: Option = row .get(4) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; - let resp_b: Option = row + let mut resp_b: Option = row .get(5) .map_err(|e| AppError::Storage(format!("read error: {e}")))?; + let id: String = row + .get(6) + .map_err(|e| AppError::Storage(format!("read error: {e}")))?; + if let Some(payload) = Journal::hydrate_sample(conn, Table::Spans, &id, 32768, 8192)? { + resp_h = payload_utf8(payload.response_headers)?; + req_h = payload_utf8(payload.request_headers)?; + req_b = payload_utf8(payload.request_body)?; + resp_b = payload_utf8(payload.response_body)?; + } let entry = out .entry((server_ip, server_port)) diff --git a/server/h-storage-duckdb/src/retention.rs b/server/h-storage-duckdb/src/retention.rs index 130ad1fa..9046d138 100644 --- a/server/h-storage-duckdb/src/retention.rs +++ b/server/h-storage-duckdb/src/retention.rs @@ -8,12 +8,20 @@ use crate::DuckDbBackend; impl DuckDbBackend { pub(crate) async fn apply_retention(&self, policy: RetentionPolicy) -> Result { + let journal_enabled = self.journal.is_some(); let calls_conn = self.write_spans_conn.clone(); let turns_conn = self.write_traces_conn.clone(); let metrics_conn = self.write_metrics_conn.clone(); let exchanges_conn = self.write_exchanges_conn.clone(); tokio::task::spawn_blocking(move || { + { + let conn = calls_conn.lock() + .map_err(|e| AppError::Storage(format!("failed to lock calls writer: {e}")))?; + if journal_enabled || crate::journal::owns_database(&conn)? { + return Err(AppError::Config("automatic row retention is not supported for journal-owned datasets; manage the database and journal directory together".into())); + } + } let mut report = RetentionReport::default(); if let Some(cutoff) = policy.spans_before { @@ -106,14 +114,14 @@ impl DuckDbBackend { #[cfg(test)] mod tests { use crate::DuckDbBackend; - use std::net::IpAddr; - use std::time::{Duration, SystemTime}; use h_llm::model::{ApiType, LlmCall}; use h_llm::wire_apis as wa; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_storage::retention::RetentionPolicy; use h_storage::StorageBackend; use h_turn::{Trace, TraceStatus}; + use std::net::IpAddr; + use std::time::{Duration, SystemTime}; fn mk_call(id: &str, request_time_us: i64) -> LlmCall { LlmCall { diff --git a/server/h-storage-duckdb/src/schema.rs b/server/h-storage-duckdb/src/schema.rs index af06fb94..7b3eff25 100644 --- a/server/h-storage-duckdb/src/schema.rs +++ b/server/h-storage-duckdb/src/schema.rs @@ -1,8 +1,8 @@ //! DDL constants for the DuckDB-backed schema, plus the `init()` bootstrap //! that creates every table and runs forward-compatible migrations. -use tracing::info; use h_common::error::{AppError, Result}; +use tracing::info; use crate::DuckDbBackend; @@ -180,6 +180,7 @@ pub(crate) async fn init(backend: &DuckDbBackend) -> Result<()> { // Any writer works — they share the same DuckDB instance. Using the // calls writer keeps init deterministic. let conn = backend.write_spans_conn.clone(); + let journal_enabled = backend.journal.is_some(); tokio::task::spawn_blocking(move || { let conn = conn .lock() @@ -289,7 +290,7 @@ pub(crate) async fn init(backend: &DuckDbBackend) -> Result<()> { // table. TPOT is reconstructed per-call (complete_time - // response_time) / output_tokens; active_calls_* can't be // reconstructed (live concurrency sampling) and stays 0. - if rollup_empty_but_calls_present(&conn) { + if !journal_enabled && !crate::journal::owns_database(&conn)? && rollup_empty_but_calls_present(&conn) { tracing::info!( "llm_metrics is empty but llm_calls has rows — back-filling rollup history" ); diff --git a/server/h-storage-duckdb/src/sessions.rs b/server/h-storage-duckdb/src/sessions.rs index 406ac061..54769b09 100644 --- a/server/h-storage-duckdb/src/sessions.rs +++ b/server/h-storage-duckdb/src/sessions.rs @@ -501,8 +501,8 @@ impl DuckDbBackend { } } } - let user_map = extract_full_text_batch(&conn, ExtractKind::User, &need_user); - let asst_map = extract_full_text_batch(&conn, ExtractKind::Assistant, &need_assistant); + let user_map = extract_full_text_batch(&conn, ExtractKind::User, &need_user)?; + let asst_map = extract_full_text_batch(&conn, ExtractKind::Assistant, &need_assistant)?; let mut items: Vec = Vec::with_capacity(fetched.len()); for t in fetched { @@ -606,12 +606,7 @@ mod tests { DuckDbBackend::open(":memory:").unwrap() } - fn sample_turn( - turn_id: &str, - session_id: &str, - agent_kind: &str, - start_us: i64, - ) -> Trace { + fn sample_turn(turn_id: &str, session_id: &str, agent_kind: &str, start_us: i64) -> Trace { Trace { source_id: String::new(), turn_id: turn_id.into(), @@ -686,7 +681,10 @@ mod tests { }; let page_single = backend.query_sessions(&query_single).await.unwrap(); assert_eq!(page_single.items.len(), 2); - assert!(page_single.items.iter().all(|s| s.agent_kind == "claude-cli")); + assert!(page_single + .items + .iter() + .all(|s| s.agent_kind == "claude-cli")); // Multiple kinds → union. (The bug: a raw-CSV exact-match returns 0 here.) let query_multi = SessionListQuery { @@ -698,7 +696,11 @@ mod tests { }; let page_multi = backend.query_sessions(&query_multi).await.unwrap(); assert_eq!(page_multi.items.len(), 3); - let kinds: Vec<_> = page_multi.items.iter().map(|s| s.agent_kind.as_str()).collect(); + let kinds: Vec<_> = page_multi + .items + .iter() + .map(|s| s.agent_kind.as_str()) + .collect(); assert!(kinds.contains(&"claude-cli") && kinds.contains(&"codex-cli")); assert!(!kinds.contains(&"openclaw")); @@ -711,6 +713,14 @@ mod tests { cursor: None, page_size: 100, }; - assert_eq!(backend.query_sessions(&query_all).await.unwrap().items.len(), 4); + assert_eq!( + backend + .query_sessions(&query_all) + .await + .unwrap() + .items + .len(), + 4 + ); } } diff --git a/server/h-storage-duckdb/src/turns.rs b/server/h-storage-duckdb/src/turns.rs index 854ee4a7..938f4dfa 100644 --- a/server/h-storage-duckdb/src/turns.rs +++ b/server/h-storage-duckdb/src/turns.rs @@ -120,6 +120,44 @@ fn prepare_turn(t: Trace) -> PreparedTurn { } } +impl PreparedTurn { + fn parameters(&self) -> Vec<&dyn duckdb::ToSql> { + let p = self; + vec![ + &p.turn_id, + &p.source_id, + &p.session_id, + &p.wire_api, + &p.agent_kind, + &p.client_ip, + &p.server_ip, + &p.start_time, + &p.end_time, + &p.duration_ms, + &p.call_count, + &p.models_used, + &p.subagents_used, + &p.total_input_tokens, + &p.total_output_tokens, + &p.total_cache_read_input_tokens, + &p.total_cache_creation_input_tokens, + &p.total_cost_usd, + &p.status, + &p.final_finish_reason, + &p.user_input_preview, + &p.user_call_id, + &p.final_answer_preview, + &p.final_call_id, + &p.span_ids, + &p.metadata, + &p.tool_surfaces_json, + &p.tool_call_total, + &p.agent_topology, + &p.suspicious_skills_json, + ] + } +} + impl DuckDbBackend { pub(crate) async fn write_traces(&self, turns: Vec) -> Result<()> { if turns.is_empty() { @@ -136,9 +174,18 @@ impl DuckDbBackend { } } let conn = self.write_traces_conn.clone(); + let journal = self.journal.clone(); tokio::task::spawn_blocking(move || { let prepared: Vec = turns.into_iter().map(prepare_turn).collect(); + if let Some(journal) = journal { + let rows = prepared + .iter() + .map(|p| crate::journal::row(crate::journal::Table::Traces, &p.parameters())) + .collect::>>()?; + return journal.append(rows); + } + let conn = conn .lock() .map_err(|e| AppError::Storage(format!("failed to lock writer: {e}")))?; @@ -147,38 +194,7 @@ impl DuckDbBackend { .map_err(|e| AppError::Storage(format!("failed to create turns appender: {e}")))?; for p in &prepared { appender - .append_row(duckdb::params![ - p.turn_id, - p.source_id, - p.session_id, - p.wire_api, - p.agent_kind, - p.client_ip, - p.server_ip, - p.start_time, - p.end_time, - p.duration_ms, - p.call_count, - p.models_used, - p.subagents_used, - p.total_input_tokens, - p.total_output_tokens, - p.total_cache_read_input_tokens, - p.total_cache_creation_input_tokens, - p.total_cost_usd, - p.status, - p.final_finish_reason, - p.user_input_preview, - p.user_call_id, - p.final_answer_preview, - p.final_call_id, - p.span_ids, - p.metadata, - p.tool_surfaces_json, - p.tool_call_total, - p.agent_topology, - p.suspicious_skills_json, - ]) + .append_row(p.parameters().as_slice()) .map_err(|e| AppError::Storage(format!("failed to append turn: {e}")))?; } appender @@ -570,7 +586,7 @@ impl DuckDbBackend { &agent_kind, user_call_id.as_deref(), ExtractKind::User, - ) + )? .or_else(|| user_input_preview.clone()), }; let final_answer = match final_answer_preview.as_deref() { @@ -580,7 +596,7 @@ impl DuckDbBackend { &agent_kind, final_call_id.as_deref(), ExtractKind::Assistant, - ) + )? .or_else(|| final_answer_preview.clone()), }; diff --git a/server/h-storage-duckdb/src/util.rs b/server/h-storage-duckdb/src/util.rs index edda61eb..9dc27806 100644 --- a/server/h-storage-duckdb/src/util.rs +++ b/server/h-storage-duckdb/src/util.rs @@ -17,6 +17,37 @@ use h_llm::model::{ApiType, LlmCall}; use h_llm::profile::{parse_bodies, CallCtx}; use h_llm::wire_apis as wa; +use crate::journal::{Journal, Table}; + +pub(crate) struct TextPayload { + pub request_body: Option, + pub response_body: Option, + pub request_headers: Option, + pub response_headers: Option, + pub tokens_estimated: bool, +} + +pub(crate) fn payload_utf8(bytes: Option>) -> Result> { + bytes + .map(String::from_utf8) + .transpose() + .map_err(|e| AppError::Storage(format!("journal text payload is not UTF-8: {e}"))) +} + +pub(crate) fn hydrate_span_payload(conn: &Connection, id: &str) -> Result> { + Journal::hydrate(conn, Table::Spans, id)? + .map(|payload| { + Ok(TextPayload { + request_body: payload_utf8(payload.request_body)?, + response_body: payload_utf8(payload.response_body)?, + request_headers: payload_utf8(payload.request_headers)?, + response_headers: payload_utf8(payload.response_headers)?, + tokens_estimated: payload.tokens_estimated, + }) + }) + .transpose() +} + pub(crate) use h_storage::convert::{ derive_tokens_estimated, headers_to_json, parse_json_string_list, }; @@ -96,24 +127,38 @@ pub(crate) fn extract_full_text( agent_kind: &str, call_id: Option<&str>, kind: ExtractKind, -) -> Option { - let call_id = call_id?; +) -> Result> { + let Some(call_id) = call_id else { + return Ok(None); + }; let registry = build_default_registry(); - let profile = registry.find_by_name(agent_kind)?; + let Some(profile) = registry.find_by_name(agent_kind) else { + return Ok(None); + }; let sql = match kind { ExtractKind::User => "SELECT request_body, wire_api FROM spans WHERE id = ?", ExtractKind::Assistant => "SELECT response_body, wire_api FROM spans WHERE id = ?", }; - let (body, wire_api_stored): (Option, String) = conn - .query_row(sql, duckdb::params![call_id], |row| { + let (inline_body, wire_api_stored): (Option, String) = + match conn.query_row(sql, duckdb::params![call_id], |row| { Ok((row.get(0)?, row.get(1)?)) - }) - .ok()?; - // Resolve the stored value back to its static constant. An unknown value - // means the DB has a wire_api this binary no longer knows about — drop - // the extraction rather than fabricate one. - let wire_api = wa::by_name(&wire_api_stored)?; + }) { + Ok(value) => value, + Err(duckdb::Error::QueryReturnedNoRows) => return Ok(None), + Err(e) => return Err(AppError::Storage(format!("read full text: {e}"))), + }; + // Unknown historical wire APIs cannot be extracted by this binary. + let Some(wire_api) = wa::by_name(&wire_api_stored) else { + return Ok(None); + }; + let body = match hydrate_span_payload(conn, call_id)? { + Some(payload) => match kind { + ExtractKind::User => payload.request_body, + ExtractKind::Assistant => payload.response_body, + }, + None => inline_body, + }; let (request_body, response_body) = match kind { ExtractKind::User => (body, None), ExtractKind::Assistant => (None, body), @@ -160,10 +205,10 @@ pub(crate) fn extract_full_text( }; let (req, resp) = parse_bodies(&call); let ctx = CallCtx::new(&call, req.as_ref(), resp.as_ref()); - match kind { + Ok(match kind { ExtractKind::User => profile.extract_user_input(&ctx), ExtractKind::Assistant => profile.extract_assistant_text(&ctx), - } + }) } /// Batch version of `extract_full_text`. Given `(agent_kind, call_id)` pairs @@ -178,11 +223,11 @@ pub(crate) fn extract_full_text_batch( conn: &Connection, kind: ExtractKind, requests: &[(String, String)], // (agent_kind, call_id) -) -> std::collections::HashMap { +) -> Result> { use std::collections::HashMap; let mut out: HashMap = HashMap::new(); if requests.is_empty() { - return out; + return Ok(out); } // Build agent_kind lookup keyed by call_id (last-writer-wins if a call id @@ -202,23 +247,28 @@ pub(crate) fn extract_full_text_batch( let registry = build_default_registry(); - let Ok(mut stmt) = conn.prepare(&sql) else { - return out; - }; + let mut stmt = conn + .prepare(&sql) + .map_err(|e| AppError::Storage(format!("prepare full text: {e}")))?; let params: Vec<&dyn duckdb::ToSql> = span_ids.iter().map(|s| s as &dyn duckdb::ToSql).collect(); - let Ok(mut rows) = stmt.query(duckdb::params_from_iter(params.iter().copied())) else { - return out; - }; + let mut rows = stmt + .query(duckdb::params_from_iter(params.iter().copied())) + .map_err(|e| AppError::Storage(format!("query full text: {e}")))?; - while let Ok(Some(row)) = rows.next() { - let Ok(id): std::result::Result = row.get(0) else { - continue; - }; - let Ok(wire_api_stored): std::result::Result = row.get(1) else { - continue; - }; - let body: Option = row.get(2).ok(); + while let Some(row) = rows + .next() + .map_err(|e| AppError::Storage(format!("read full text: {e}")))? + { + let id: String = row + .get(0) + .map_err(|e| AppError::Storage(format!("read full text id: {e}")))?; + let wire_api_stored: String = row + .get(1) + .map_err(|e| AppError::Storage(format!("read full text wire API: {e}")))?; + let inline_body: Option = row + .get(2) + .map_err(|e| AppError::Storage(format!("read inline full text: {e}")))?; let Some(wire_api) = wa::by_name(&wire_api_stored) else { continue; }; @@ -228,6 +278,13 @@ pub(crate) fn extract_full_text_batch( let Some(profile) = registry.find_by_name(agent_kind) else { continue; }; + let body = match hydrate_span_payload(conn, &id)? { + Some(payload) => match kind { + ExtractKind::User => payload.request_body, + ExtractKind::Assistant => payload.response_body, + }, + None => inline_body, + }; let (request_body, response_body) = match kind { ExtractKind::User => (body, None), @@ -281,7 +338,7 @@ pub(crate) fn extract_full_text_batch( } } - out + Ok(out) } /// Convert a `SystemTime` into a DuckDB microsecond-precision timestamp value. diff --git a/server/h-storage/src/backend.rs b/server/h-storage/src/backend.rs index 91244cb4..285f95b8 100644 --- a/server/h-storage/src/backend.rs +++ b/server/h-storage/src/backend.rs @@ -2,7 +2,7 @@ use async_trait::async_trait; use h_llm::model::LlmCall; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_protocol::HttpExchange; -use h_turn::{Trace, PairCandidate}; +use h_turn::{PairCandidate, Trace}; use crate::query::*; use crate::retention::{RetentionPolicy, RetentionReport}; @@ -14,6 +14,27 @@ pub trait StorageBackend: Send + Sync { /// Create tables/schemas if they don't exist. async fn init(&self) -> Result<()>; + /// True when write acknowledgements refer to a durable local journal. + /// Such an ingestion failure must stop the pipeline instead of dropping a batch. + fn durable_ingestion(&self) -> bool { + false + } + + /// Wait for accepted durable records to become visible in the query index. + async fn flush_pending(&self) -> Result<()> { + Ok(()) + } + + /// Keep wide and finish metrics in one durable ingestion unit when supported. + async fn write_metric_batch( + &self, + wide: Vec, + finish: Vec, + ) -> Result<()> { + self.write_metrics(wide).await?; + self.write_finish_metrics(finish).await + } + /// Batch-write LlmCall records. Takes ownership so the backend can move /// the batch into a blocking task without an extra clone. async fn write_spans(&self, calls: Vec) -> Result<()>; @@ -172,6 +193,17 @@ pub trait StorageBackend: Send + Sync { // `h_turn::pair_all` over the projection. For each pair it writes a // JSON patch into both turns' `metadata` field. + /// Optional backend-owned bounded sweep for the fixed `[start_us, end_us)` + /// window. `None` retains the shared classifier/update path. Errors propagate + /// without falling back: a failed backend sweep may already have writes. + async fn sweep_pair_window( + &self, + _start_us: i64, + _end_us: i64, + ) -> Result> { + Ok(None) + } + /// Return a minimal projection of `agent_turns` rows in /// `[start_us, end_us)` suitable for `h_turn::pair_all`. Rows whose /// `metadata` already carries `proxy.role` are excluded — once a turn diff --git a/server/h-storage/src/buffer.rs b/server/h-storage/src/buffer.rs index 243c3b31..3979d14f 100644 --- a/server/h-storage/src/buffer.rs +++ b/server/h-storage/src/buffer.rs @@ -38,6 +38,7 @@ pub struct WriteBuffer { flush_interval: Duration, metrics: Option, err_throttle: ThrottledWarn, + fatal_errors: bool, } impl WriteBuffer { @@ -56,9 +57,16 @@ impl WriteBuffer { flush_interval, metrics, err_throttle: ThrottledWarn::new(FLUSH_ERR_WARN_THROTTLE), + fatal_errors: false, } } + /// Stop the supervised pipeline if a durable-ingestion acknowledgement fails. + pub fn fail_on_error(mut self, enabled: bool) -> Self { + self.fatal_errors = enabled; + self + } + /// Run the buffer loop. Calls `flush_fn` with each batch. /// Returns once the upstream channel closes and any remaining batch has /// been flushed. @@ -140,6 +148,9 @@ impl WriteBuffer { if let Some(ref m) = self.metrics { m.errors.inc(); } + if self.fatal_errors { + panic!("durable storage ingestion failed for {entity}: {e}"); + } if let Some(suppressed) = self.err_throttle.tick() { if suppressed > 0 { error!( @@ -308,6 +319,31 @@ mod tests { task.await.unwrap(); } + #[tokio::test] + async fn durable_failure_stops_without_accepting_the_next_batch() { + let (tx, rx) = mpsc::channel::(4); + let attempts = Arc::new(AtomicUsize::new(0)); + let seen = attempts.clone(); + let task = tokio::spawn(async move { + WriteBuffer::new("durable-test", rx, 1, Duration::from_secs(60), None) + .fail_on_error(true) + .run(move |_| { + seen.fetch_add(1, Ordering::SeqCst); + async { + Err(h_common::error::AppError::Storage( + "synthetic durable failure".into(), + )) + } + }) + .await; + }); + tx.send(1).await.unwrap(); + tx.send(2).await.unwrap(); + drop(tx); + assert!(task.await.unwrap_err().is_panic()); + assert_eq!(attempts.load(Ordering::SeqCst), 1); + } + #[tokio::test] // @scenario STORAGE-DURABILITY-001 unit async fn test_flush_failure_does_not_stop_loop() { diff --git a/server/h-storage/src/lib.rs b/server/h-storage/src/lib.rs index 4e75b2e9..3df46e0b 100644 --- a/server/h-storage/src/lib.rs +++ b/server/h-storage/src/lib.rs @@ -10,7 +10,9 @@ pub mod sink; pub use backend::StorageBackend; pub use buffer::WriteBuffer; -pub use pair_sweeper::{spawn_pair_sweeper, sweep_once, PairSweeperConfig, SweepStats}; +pub use pair_sweeper::{ + spawn_pair_sweeper, spawn_pair_sweeper_with_shutdown, sweep_once, PairSweeperConfig, SweepStats, +}; pub use query::*; pub use retention::{policy_from_config, spawn_retention_task, RetentionPolicy, RetentionReport}; pub use sink::{spawn_storage_sink_stage, StorageSinkConfig}; diff --git a/server/h-storage/src/pair_sweeper.rs b/server/h-storage/src/pair_sweeper.rs index 9ad22268..b60ce4d5 100644 --- a/server/h-storage/src/pair_sweeper.rs +++ b/server/h-storage/src/pair_sweeper.rs @@ -33,6 +33,7 @@ use std::sync::Arc; use std::time::Duration; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use h_turn::proxy_pair::group_all; @@ -65,30 +66,60 @@ impl Default for PairSweeperConfig { } } -/// Spawn the sweeper. Runs until `storage` is dropped from every other -/// holder AND the inner sleep wakes — in practice the task lives for the -/// process lifetime. Errors during a sweep are logged and the sweeper -/// continues; one bad sweep should never take down the pipeline. +/// Spawn a process-lifetime sweeper. It holds its own storage reference and +/// runs until explicitly aborted or the runtime stops. Use +/// [`spawn_pair_sweeper_with_shutdown`] when a final sweep is required. +/// Periodic failures are logged and retried on the next tick. pub fn spawn_pair_sweeper( cfg: PairSweeperConfig, storage: Arc, +) -> JoinHandle<()> { + spawn_pair_sweeper_with_shutdown(cfg, storage, CancellationToken::new()) +} + +/// Spawn a cooperatively stopped sweeper. Cancel `shutdown` after the storage +/// sink has drained. Stop is observed only between complete sweep/checkpoint +/// batches, then one final sweep/checkpoint runs even before the first tick. +/// Final maintenance failures panic so the supervising join observes failure. +pub fn spawn_pair_sweeper_with_shutdown( + cfg: PairSweeperConfig, + storage: Arc, + shutdown: CancellationToken, ) -> JoinHandle<()> { tokio::spawn(async move { - // Stagger the first sweep so it doesn't fire the same instant as - // service start (the DB may still be empty / cold). - tokio::time::sleep(cfg.interval).await; + let mut checkpoint_pending = false; loop { + // Stagger the first periodic sweep. Cancellation only selects + // against this sleep, never against metadata writes/checkpoints. + tokio::select! { + biased; + _ = shutdown.cancelled() => { + sweep_once(&storage, cfg.lookback).await + .unwrap_or_else(|e| panic!("pair-sweeper: final sweep failed: {e}")); + storage.checkpoint_traces_writer().await + .unwrap_or_else(|e| panic!("pair-sweeper: final CHECKPOINT failed: {e}")); + return; + } + _ = tokio::time::sleep(cfg.interval) => {} + } match sweep_once(&storage, cfg.lookback).await { - Ok(_) => { - // CHECKPOINT after each successful batch so the - // MVCC tombstone chain doesn't grow into the - // DuckDB "Failed to delete all rows from index" - // FATAL trap. Cheap when nothing to compact. - if let Err(e) = storage.checkpoint_traces_writer().await { - tracing::warn!(error = %e, "pair-sweeper: post-sweep CHECKPOINT failed"); + Ok(stats) => { + // Only our metadata UPDATEs need this extra checkpoint. + // Unchanged sweeps must not pause unrelated body writers. + checkpoint_pending |= stats.turns_tagged > 0; + if checkpoint_pending { + match storage.checkpoint_traces_writer().await { + Ok(()) => checkpoint_pending = false, + Err(e) => { + tracing::warn!(error = %e, "pair-sweeper: post-sweep CHECKPOINT failed") + } + } } } Err(e) => { + // A failed sweep may have committed earlier member updates. + // Keep maintenance pending until a checkpoint succeeds. + checkpoint_pending = true; let msg = format!("{e}"); tracing::warn!(error = %e, "pair-sweeper: sweep failed; continuing"); // The DuckDB invalidation FATAL is global to every @@ -114,7 +145,6 @@ pub fn spawn_pair_sweeper( } } } - tokio::time::sleep(cfg.interval).await; } }) } @@ -127,6 +157,9 @@ pub async fn sweep_once( ) -> h_common::error::Result { let now_us = chrono::Utc::now().timestamp_micros(); let start_us = now_us - (lookback.as_micros() as i64); + if let Some(stats) = storage.sweep_pair_window(start_us, now_us).await? { + return Ok(stats); + } let candidates = storage.query_pair_candidates(start_us, now_us).await?; let candidates_scanned = candidates.len(); let groups = group_all(&candidates); @@ -137,7 +170,9 @@ pub async fn sweep_once( let patch = g .metadata_for(&member.turn_id) .expect("member belongs to group it came from"); - storage.update_trace_metadata(&member.turn_id, patch).await?; + storage + .update_trace_metadata(&member.turn_id, patch) + .await?; turns_tagged += 1; } } @@ -166,12 +201,16 @@ mod tests { use crate::query::*; use crate::retention::{RetentionPolicy, RetentionReport}; use async_trait::async_trait; - use std::collections::HashMap; - use std::sync::Mutex as StdMutex; use h_common::error::Result; use h_llm::model::LlmCall; use h_metrics::model::{LlmFinishMetric, LlmMetric}; use h_protocol::HttpExchange; + use std::collections::HashMap; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::Mutex as StdMutex; + use tokio::sync::Notify; + use tokio_util::sync::CancellationToken; + use tokio_util::task::AbortOnDropHandle; use h_turn::proxy_pair::PairCandidate; use h_turn::Trace; @@ -179,9 +218,25 @@ mod tests { /// In-memory stub storage that holds the candidates the sweeper will /// see and records the metadata patches it writes back. Lets us test /// the sweeper without a real DB. + #[derive(Default)] struct StubStorage { candidates: Vec, + hook_mode: u8, + hook_bounds: StdMutex>, updates: StdMutex>, + pause_after_first: bool, + first_written: Notify, + release_writes: Notify, + checkpoints: AtomicUsize, + pause_checkpoint: bool, + checkpoint_started: Notify, + release_checkpoint: Notify, + fail_query: bool, + fail_checkpoint: bool, + fail_first_checkpoint: bool, + fail_update_once: AtomicBool, + sweeps: AtomicUsize, + sweep_started: Notify, } #[async_trait] @@ -340,17 +395,108 @@ mod tests { async fn apply_retention(&self, _: RetentionPolicy) -> Result { Ok(RetentionReport::default()) } + async fn sweep_pair_window(&self, start: i64, end: i64) -> Result> { + *self.hook_bounds.lock().unwrap() = Some((start, end)); + match self.hook_mode { + 1 => Ok(Some(SweepStats { + candidates_scanned: 7, + pairs_assigned: 2, + turns_tagged: 5, + })), + 2 => Err(h_common::error::AppError::Storage( + "synthetic backend sweep failure".into(), + )), + _ => Ok(None), + } + } async fn query_pair_candidates(&self, _: i64, _: i64) -> Result> { - Ok(self.candidates.clone()) + self.sweeps.fetch_add(1, Ordering::SeqCst); + self.sweep_started.notify_one(); + if self.fail_query { + return Err(h_common::error::AppError::Storage( + "candidate query failed".into(), + )); + } + // Match the real backend: paired members disappear from later sweeps. + let updates = self.updates.lock().unwrap(); + Ok(self + .candidates + .iter() + .filter(|candidate| !updates.contains_key(&candidate.turn_id)) + .cloned() + .collect()) } async fn update_trace_metadata( &self, turn_id: &str, patch: serde_json::Value, ) -> Result<()> { - self.updates.lock().unwrap().insert(turn_id.into(), patch); + let first = { + let mut updates = self.updates.lock().unwrap(); + if !updates.is_empty() && self.fail_update_once.swap(false, Ordering::SeqCst) { + return Err(h_common::error::AppError::Storage( + "metadata update failed".into(), + )); + } + updates.insert(turn_id.into(), patch); + updates.len() == 1 + }; + if self.pause_after_first && first { + self.first_written.notify_one(); + self.release_writes.notified().await; + } Ok(()) } + async fn checkpoint_traces_writer(&self) -> Result<()> { + let previous = self.checkpoints.fetch_add(1, Ordering::SeqCst); + if self.pause_checkpoint && previous == 0 { + self.checkpoint_started.notify_one(); + self.release_checkpoint.notified().await; + } + if self.fail_checkpoint || (self.fail_first_checkpoint && previous == 0) { + return Err(h_common::error::AppError::Storage( + "checkpoint failed".into(), + )); + } + Ok(()) + } + } + + // @scenario PAIR-SWEEPER-HOOK-001 unit + #[tokio::test] + async fn backend_hook_returns_stats_with_one_fixed_window() { + let backend = Arc::new(StubStorage { + hook_mode: 1, + ..Default::default() + }); + let storage: Arc = backend.clone(); + let result = sweep_once(&storage, Duration::from_secs(37)).await.unwrap(); + assert_eq!( + result, + SweepStats { + candidates_scanned: 7, + pairs_assigned: 2, + turns_tagged: 5 + } + ); + let (start, end) = backend.hook_bounds.lock().unwrap().unwrap(); + assert_eq!(end - start, 37_000_000); + assert_eq!(backend.sweeps.load(Ordering::SeqCst), 0); + assert!(backend.updates.lock().unwrap().is_empty()); + } + + // @scenario PAIR-SWEEPER-HOOK-001 unit + #[tokio::test] + async fn backend_hook_error_never_falls_back_to_legacy_discovery() { + let backend = Arc::new(StubStorage { + hook_mode: 2, + candidates: matched_pair(), + ..Default::default() + }); + let storage: Arc = backend.clone(); + assert!(sweep_once(&storage, Duration::from_secs(37)).await.is_err()); + assert_eq!(backend.sweeps.load(Ordering::SeqCst), 0); + assert!(backend.updates.lock().unwrap().is_empty()); } fn cand(id: &str, sid: &str, start: i64, end: i64, view: &str) -> PairCandidate { @@ -370,6 +516,259 @@ mod tests { } } + fn matched_pair() -> Vec { + vec![ + cand("outer", "S", 100_000, 200_000, "client->host"), + cand("inner", "S", 102_000, 199_000, "bridge->upstream"), + ] + } + + async fn wait_for_sweeps(storage: &StubStorage, count: usize) { + tokio::time::timeout(Duration::from_secs(1), async { + while storage.sweeps.load(Ordering::SeqCst) < count { + storage.sweep_started.notified().await; + } + }) + .await + .expect("periodic sweeps must run"); + } + + #[tokio::test] + async fn periodic_sweeps_without_updates_do_not_checkpoint() { + for candidates in [ + vec![], + vec![cand("lone", "S", 100_000, 200_000, "client->host")], + ] { + let storage = Arc::new(StubStorage { + candidates, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_millis(1), + ..Default::default() + }, + storage.clone(), + shutdown.clone(), + )); + wait_for_sweeps(&storage, 3).await; + assert_eq!( + storage.checkpoints.load(Ordering::SeqCst), + 0, + "read-only pairing sweeps must not pause unrelated body writers" + ); + shutdown.cancel(); + handle.await.unwrap(); + assert_eq!( + storage.checkpoints.load(Ordering::SeqCst), + 1, + "EOF must still checkpoint without any metadata updates" + ); + } + } + + #[tokio::test] + async fn periodic_checkpoint_retries_after_members_leave_candidates() { + let storage = Arc::new(StubStorage { + candidates: matched_pair(), + fail_first_checkpoint: true, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_millis(1), + ..Default::default() + }, + storage.clone(), + shutdown.clone(), + )); + wait_for_sweeps(&storage, 3).await; + assert_eq!(storage.updates.lock().unwrap().len(), 2); + assert_eq!( + storage.checkpoints.load(Ordering::SeqCst), + 2, + "retry the failed checkpoint once, then skip unchanged sweeps" + ); + shutdown.cancel(); + handle.await.unwrap(); + assert_eq!(storage.checkpoints.load(Ordering::SeqCst), 3); + } + + #[tokio::test] + async fn partial_metadata_failure_keeps_checkpoint_pending() { + let storage = Arc::new(StubStorage { + candidates: matched_pair(), + fail_update_once: AtomicBool::new(true), + ..Default::default() + }); + let shutdown = CancellationToken::new(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_millis(1), + ..Default::default() + }, + storage.clone(), + shutdown.clone(), + )); + wait_for_sweeps(&storage, 3).await; + assert_eq!(storage.updates.lock().unwrap().len(), 1); + assert_eq!( + storage.checkpoints.load(Ordering::SeqCst), + 1, + "checkpoint the partial update even when the next sweep writes nothing" + ); + shutdown.cancel(); + handle.await.unwrap(); + assert_eq!(storage.checkpoints.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn shutdown_before_first_tick_sweeps_and_checkpoints() { + let storage = Arc::new(StubStorage { + candidates: matched_pair(), + ..Default::default() + }); + let shutdown = CancellationToken::new(); + shutdown.cancel(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_secs(3600), + ..Default::default() + }, + storage.clone(), + shutdown, + )); + tokio::time::timeout(Duration::from_secs(1), handle) + .await + .expect("stop must bypass the first interval") + .unwrap(); + let updates = storage.updates.lock().unwrap(); + assert_eq!(updates.len(), 2); + assert_eq!(updates["outer"]["proxy"]["role"], "proxy_in"); + assert_eq!(updates["inner"]["proxy"]["role"], "proxy_out"); + assert_eq!(storage.checkpoints.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn shutdown_finishes_both_pair_members_before_final_sweep() { + let storage = Arc::new(StubStorage { + candidates: matched_pair(), + pause_after_first: true, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + let mut handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_millis(1), + ..Default::default() + }, + storage.clone(), + shutdown.clone(), + )); + tokio::time::timeout(Duration::from_secs(1), storage.first_written.notified()) + .await + .expect("first member must be persisted"); + shutdown.cancel(); + assert!( + tokio::time::timeout(Duration::from_millis(30), &mut handle) + .await + .is_err(), + "stop must not cancel the partially persisted pair" + ); + assert_eq!(storage.updates.lock().unwrap().len(), 1); + storage.release_writes.notify_one(); + tokio::time::timeout(Duration::from_secs(1), handle) + .await + .expect("in-flight and final sweeps must finish") + .unwrap(); + assert_eq!(storage.updates.lock().unwrap().len(), 2); + assert_eq!( + storage.checkpoints.load(Ordering::SeqCst), + 2, + "the in-flight batch and final sweep both checkpoint" + ); + } + + #[tokio::test] + async fn shutdown_does_not_cancel_inflight_checkpoint() { + let storage = Arc::new(StubStorage { + candidates: matched_pair(), + pause_checkpoint: true, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + let mut handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig { + interval: Duration::from_millis(1), + ..Default::default() + }, + storage.clone(), + shutdown.clone(), + )); + tokio::time::timeout( + Duration::from_secs(1), + storage.checkpoint_started.notified(), + ) + .await + .expect("periodic checkpoint must start"); + shutdown.cancel(); + assert!( + tokio::time::timeout(Duration::from_millis(30), &mut handle) + .await + .is_err(), + "stop must wait for the in-flight checkpoint" + ); + storage.release_checkpoint.notify_one(); + tokio::time::timeout(Duration::from_secs(1), handle) + .await + .expect("final checkpoint must finish") + .unwrap(); + assert_eq!(storage.checkpoints.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn final_sweep_failure_is_observable() { + let storage = Arc::new(StubStorage { + fail_query: true, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + shutdown.cancel(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig::default(), + storage, + shutdown, + )); + let error = tokio::time::timeout(Duration::from_secs(1), handle) + .await + .expect("failed final sweep must terminate") + .expect_err("must report failure"); + assert!(error.is_panic()); + } + + // @scenario STORAGE-DRAIN-001 fault + #[tokio::test] + async fn final_checkpoint_failure_is_observable() { + let storage = Arc::new(StubStorage { + fail_checkpoint: true, + ..Default::default() + }); + let shutdown = CancellationToken::new(); + shutdown.cancel(); + let handle = AbortOnDropHandle::new(spawn_pair_sweeper_with_shutdown( + PairSweeperConfig::default(), + storage, + shutdown, + )); + let error = tokio::time::timeout(Duration::from_secs(1), handle) + .await + .expect("failed final checkpoint must terminate") + .expect_err("must report failure"); + assert!(error.is_panic()); + } + #[tokio::test] async fn sweep_once_writes_metadata_for_matched_pair() { // Real-data shape: outer leg encloses inner, network views differ. @@ -379,6 +778,7 @@ mod tests { cand("inner", "S", 102_000, 199_000, "bridge->upstream"), ], updates: StdMutex::new(HashMap::new()), + ..Default::default() }) as Arc; let stats = sweep_once(&stub, Duration::from_secs(60)).await.unwrap(); assert_eq!(stats.pairs_assigned, 1); @@ -400,6 +800,7 @@ mod tests { cand("inner", "S", 348_296_000, 350_587_000, "bridge->upstream"), ], updates: StdMutex::new(HashMap::new()), + ..Default::default() }); let stub = stub_inner.clone() as Arc; let stats = sweep_once(&stub, Duration::from_secs(3600)).await.unwrap(); @@ -454,6 +855,7 @@ mod tests { cand("c_hop", "S", 1_002_000, 2_999_000, "172.17.0.1->172.17.0.4"), ], updates: StdMutex::new(HashMap::new()), + ..Default::default() }); let stub = stub_inner.clone() as Arc; let stats = sweep_once(&stub, Duration::from_secs(3600)).await.unwrap(); @@ -493,6 +895,7 @@ mod tests { let stub = Arc::new(StubStorage { candidates: vec![cand("solo", "S", 0, 1000, "v")], updates: StdMutex::new(HashMap::new()), + ..Default::default() }) as Arc; let stats = sweep_once(&stub, Duration::from_secs(60)).await.unwrap(); assert_eq!(stats.pairs_assigned, 0); diff --git a/server/h-storage/src/sink.rs b/server/h-storage/src/sink.rs index b5f6e755..b94e37a7 100644 --- a/server/h-storage/src/sink.rs +++ b/server/h-storage/src/sink.rs @@ -71,6 +71,7 @@ pub fn spawn_storage_sink_stage( metrics: MetricsWorker, ) -> JoinHandle<()> { let flush_interval = Duration::from_millis(config.flush_interval_ms); + let durable = backend.durable_ingestion(); // One BufferMetrics per entity so operators can see which stream dominates // in the storage line. flush_errors stays shared — it's near-zero in @@ -140,7 +141,8 @@ pub fn spawn_storage_sink_stage( config.batch_size, flush_interval, Some(calls_buf_metrics), - ); + ) + .fail_on_error(durable); let calls_task = tokio::spawn(async move { calls_buffer .run(move |batch| { @@ -157,7 +159,8 @@ pub fn spawn_storage_sink_stage( config.batch_size, flush_interval, Some(turns_buf_metrics), - ); + ) + .fail_on_error(durable); let turns_task = tokio::spawn(async move { turns_buffer .run(move |batch| { @@ -174,7 +177,8 @@ pub fn spawn_storage_sink_stage( config.batch_size, flush_interval, Some(metrics_buf_metrics), - ); + ) + .fail_on_error(durable); let metrics_task = tokio::spawn(async move { metrics_buffer .run(move |batch: Vec| { @@ -189,10 +193,7 @@ pub fn spawn_storage_sink_stage( wide.push(item.metric); finish.extend(item.finish_metrics); } - async move { - b.write_metrics(wide).await?; - b.write_finish_metrics(finish).await - } + async move { b.write_metric_batch(wide, finish).await } }) .await; }); @@ -205,12 +206,16 @@ pub fn spawn_storage_sink_stage( config.batch_size, flush_interval, Some(exch_buf_metrics), - ); + ) + .fail_on_error(durable); let exch_task = tokio::spawn(async move { exch_buffer .run(move |batch| { let b = exch_storage.clone(); - let batch = batch.into_iter().map(|x| cap_exchange(x, &body_cap)).collect(); + let batch = batch + .into_iter() + .map(|x| cap_exchange(x, &body_cap)) + .collect(); async move { b.write_exchanges(batch).await } }) .await; @@ -220,18 +225,21 @@ pub fn spawn_storage_sink_stage( // Propagate inner-task panics by unwrapping join errors — otherwise // the outer task would exit cleanly and hide the failure from // supervise(). - let (ru, rc, rt, rm, re) = tokio::join!( - calls_unwrap, - calls_task, - turns_task, - metrics_task, - exch_task - ); - ru.expect("storage_sink: calls unwrap task panicked"); - rc.expect("storage_sink: calls writer panicked"); - rt.expect("storage_sink: turns writer panicked"); - rm.expect("storage_sink: metrics writer panicked"); - re.expect("storage_sink: exchanges writer panicked"); + // Dropping any wrapper aborts its sibling task, so a failed durable + // append reaches the supervisor without waiting for source EOF. + use tokio_util::task::AbortOnDropHandle; + tokio::try_join!( + AbortOnDropHandle::new(calls_unwrap), + AbortOnDropHandle::new(calls_task), + AbortOnDropHandle::new(turns_task), + AbortOnDropHandle::new(metrics_task), + AbortOnDropHandle::new(exch_task), + ) + .expect("storage_sink: writer task failed"); + backend + .flush_pending() + .await + .expect("storage_sink: durable index did not drain"); }) } @@ -239,21 +247,26 @@ pub fn spawn_storage_sink_stage( mod tests { use super::*; use crate::query::{ - AgentActivityPoint, AgentActivityQuery, AgentKindSummary, AgentSummaryQuery, SpanDetail, - SpansPage, SpansQuery, DistinctAgentKindsQuery, DistinctFinishReason, - FinishReasonTimeseries, FinishReasonsQuery, HttpExchangeDetail, HttpExchangesPage, - HttpExchangesQuery, MetricsModelRow, MetricsModelsQuery, MetricsSummaryQuery, - MetricsSummaryRow, MetricsTimeseriesQuery, MetricsTimeseriesRow, ServiceRow, ServicesQuery, - ServicesTopology, ServicesTopologyQuery, SessionDetail, SessionListQuery, SessionTracesPage, - SessionTracesQuery, SessionsPage, TraceSpanItem, TraceDetail, TracesPage, TracesQuery, + AgentActivityPoint, AgentActivityQuery, AgentKindSummary, AgentSummaryQuery, + DistinctAgentKindsQuery, DistinctFinishReason, FinishReasonTimeseries, FinishReasonsQuery, + HttpExchangeDetail, HttpExchangesPage, HttpExchangesQuery, MetricsModelRow, + MetricsModelsQuery, MetricsSummaryQuery, MetricsSummaryRow, MetricsTimeseriesQuery, + MetricsTimeseriesRow, ServiceRow, ServicesQuery, ServicesTopology, ServicesTopologyQuery, + SessionDetail, SessionListQuery, SessionTracesPage, SessionTracesQuery, SessionsPage, + SpanDetail, SpansPage, SpansQuery, TraceDetail, TraceSpanItem, TracesPage, TracesQuery, }; use async_trait::async_trait; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::Arc; use h_common::error::Result; use h_common::internal_metrics::MetricsSystem; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + #[derive(Default)] struct CountingBackend { + durable: bool, + fail_write: bool, + fail_drain: bool, + drains: Arc, calls: Arc, turns: Arc, metrics: Arc, @@ -262,10 +275,27 @@ mod tests { #[async_trait] impl StorageBackend for CountingBackend { + fn durable_ingestion(&self) -> bool { + self.durable + } + async fn flush_pending(&self) -> Result<()> { + self.drains.fetch_add(1, Ordering::SeqCst); + if self.fail_drain { + return Err(h_common::error::AppError::Storage( + "synthetic index failure".into(), + )); + } + Ok(()) + } async fn init(&self) -> Result<()> { Ok(()) } async fn write_spans(&self, batch: Vec) -> Result<()> { + if self.fail_write { + return Err(h_common::error::AppError::Storage( + "synthetic append failure".into(), + )); + } self.calls.fetch_add(batch.len(), Ordering::SeqCst); Ok(()) } @@ -445,6 +475,7 @@ mod tests { turns: Arc::new(AtomicUsize::new(0)), metrics: Arc::new(AtomicUsize::new(0)), exchanges: Arc::new(AtomicUsize::new(0)), + ..Default::default() }; let (calls_count, turns_count, metrics_count, exchanges_count) = ( counts.calls.clone(), @@ -508,6 +539,113 @@ mod tests { assert_eq!(exchanges_count.load(Ordering::SeqCst), 3); } + // @scenario STORAGE-DRAIN-001 fault + #[tokio::test] + async fn durable_sink_propagates_append_failure_before_source_eof() { + let backend = Arc::new(CountingBackend { + durable: true, + fail_write: true, + ..Default::default() + }); + let (calls_tx, calls_rx) = mpsc::channel(2); + let (turns_tx, turns_rx) = mpsc::channel(2); + let (metrics_tx, metrics_rx) = mpsc::channel(2); + let (exch_tx, exch_rx) = mpsc::channel(2); + let mut system = MetricsSystem::new(); + let worker = system.register_worker( + "storage_sink", + &[ + Metric::StorageBufferedCalls, + Metric::StorageBufferedTurns, + Metric::StorageBufferedMetrics, + Metric::StorageBufferedHttpExchanges, + Metric::StorageFlushedCalls, + Metric::StorageFlushedTurns, + Metric::StorageFlushedMetrics, + Metric::StorageFlushedHttpExchanges, + Metric::StorageFlushErrors, + ], + ); + let _service = system.start(); + let handle = spawn_storage_sink_stage( + StorageSinkConfig { + batch_size: 1, + ..Default::default() + }, + calls_rx, + turns_rx, + metrics_rx, + exch_rx, + backend.clone(), + worker, + ); + calls_tx.send(Arc::new(dummy_call(0))).await.unwrap(); + let failed = tokio::time::timeout(std::time::Duration::from_secs(2), handle) + .await + .expect("a failed append must reach supervision while producers remain open"); + assert!(failed.unwrap_err().is_panic()); + assert_eq!(backend.drains.load(Ordering::SeqCst), 0); + drop((calls_tx, turns_tx, metrics_tx, exch_tx)); + } + + // @scenario STORAGE-DRAIN-001 fault + #[tokio::test] + async fn durable_sink_drains_after_writes_and_surfaces_index_failure() { + let backend = Arc::new(CountingBackend { + durable: true, + fail_drain: true, + ..Default::default() + }); + let (calls_tx, calls_rx) = mpsc::channel(2); + let (turns_tx, turns_rx) = mpsc::channel(2); + let (metrics_tx, metrics_rx) = mpsc::channel(2); + let (exch_tx, exch_rx) = mpsc::channel(2); + let mut system = MetricsSystem::new(); + let worker = system.register_worker( + "storage_sink", + &[ + Metric::StorageBufferedCalls, + Metric::StorageBufferedTurns, + Metric::StorageBufferedMetrics, + Metric::StorageBufferedHttpExchanges, + Metric::StorageFlushedCalls, + Metric::StorageFlushedTurns, + Metric::StorageFlushedMetrics, + Metric::StorageFlushedHttpExchanges, + Metric::StorageFlushErrors, + ], + ); + let _service = system.start(); + let handle = spawn_storage_sink_stage( + StorageSinkConfig { + batch_size: 4, + ..Default::default() + }, + calls_rx, + turns_rx, + metrics_rx, + exch_rx, + backend.clone(), + worker, + ); + calls_tx.send(Arc::new(dummy_call(0))).await.unwrap(); + assert_eq!(backend.drains.load(Ordering::SeqCst), 0); + drop((calls_tx, turns_tx, metrics_tx, exch_tx)); + assert!( + tokio::time::timeout(std::time::Duration::from_secs(2), handle) + .await + .unwrap() + .unwrap_err() + .is_panic() + ); + assert_eq!( + backend.calls.load(Ordering::SeqCst), + 1, + "final writer batch precedes index drain" + ); + assert_eq!(backend.drains.load(Ordering::SeqCst), 1); + } + fn small_cap() -> BodyCapConfig { BodyCapConfig { enabled: true, @@ -558,10 +696,10 @@ mod tests { fn dummy_exchange(i: usize) -> HttpExchange { use bytes::Bytes; - use std::net::IpAddr; - use std::sync::Arc; use h_protocol::model::{HttpRequestData, HttpResponseData}; use h_protocol::net::FlowKey; + use std::net::IpAddr; + use std::sync::Arc; let client_ip: IpAddr = "127.0.0.1".parse().unwrap(); let server_ip: IpAddr = "127.0.0.1".parse().unwrap(); let request = Arc::new(HttpRequestData { @@ -598,9 +736,9 @@ mod tests { } fn dummy_call(i: usize) -> LlmCall { - use std::net::IpAddr; use h_llm::model::ApiType; use h_llm::wire_apis as wa; + use std::net::IpAddr; LlmCall { source_id: String::new(), id: format!("c-{i}"), diff --git a/server/h-turn/src/model.rs b/server/h-turn/src/model.rs index dac6a04a..483fb8b3 100644 --- a/server/h-turn/src/model.rs +++ b/server/h-turn/src/model.rs @@ -46,9 +46,9 @@ impl fmt::Display for TraceStatus { } /// In-memory registry of currently-in-flight agent turns, keyed by -/// `turn_id`. Each `TurnTracker` writes a snapshot here on every ingest -/// (replacing any prior snapshot for the same turn_id), and removes the -/// entry when the turn finalizes. The `h-api` `/api/agent-turns` handler +/// `turn_id`. Each `TurnTracker` updates its head partition's snapshot on +/// ingest, mutating ordered appends in place, and removes the entry when that +/// partition finalizes, is discarded, or its tracker exits. The API handler /// reads this registry, filters by the requested time window, and unions /// the result with rows persisted in DuckDB so the console sees both /// in-progress and finalized turns in one list. @@ -91,7 +91,7 @@ pub struct Trace { pub server_ip: IpAddr, pub start_time_us: i64, // first call's request_time - pub end_time_us: i64, // last call's complete_time (or request_time if no resp) + pub end_time_us: i64, // max complete_time, response_time or request_time across calls pub duration_ms: u64, // (end_time_us - start_time_us) / 1000 pub call_count: u32, @@ -120,8 +120,8 @@ pub struct Trace { pub final_call_id: Option, /// Ordered list of `LlmCall.id` values that belong to this turn. - /// Populated by `TurnTracker::ingest` in ingest order. Replaces the - /// Phase-1 `LlmCall.turn_id` back-reference. + /// Ordered by request_time, retaining insertion order for equal timestamps. + /// Replaces the Phase-1 `LlmCall.turn_id` back-reference. pub span_ids: Vec, pub metadata: serde_json::Value, // future extension point; empty object by default diff --git a/server/h-turn/src/stage.rs b/server/h-turn/src/stage.rs index 6922654b..9c6c0b70 100644 --- a/server/h-turn/src/stage.rs +++ b/server/h-turn/src/stage.rs @@ -220,6 +220,8 @@ mod tests { } } + include!("stage_longrun_tests.rs"); + #[tokio::test] async fn single_shard_produces_turn() { let (shard_tx, shard_rx) = mpsc::channel::(16); diff --git a/server/h-turn/src/stage_longrun_tests.rs b/server/h-turn/src/stage_longrun_tests.rs new file mode 100644 index 00000000..63c0a461 --- /dev/null +++ b/server/h-turn/src/stage_longrun_tests.rs @@ -0,0 +1,84 @@ +#[tokio::test] +async fn longrun_eof_replay_drains_64_groups_without_ghosts() { + let registry = crate::new_active_trace_registry(); + let (input, receiver) = mpsc::channel(128); + let (output, mut turns) = mpsc::channel(128); + let mut metrics = MetricsSystem::new(); + let handles = spawn_turn_stage( + TrackerConfig::default(), + vec![receiver], + output, + &mut metrics, + Some(registry.clone()), + ); + let _svc = metrics.start(); + for group in 0..64 { + for (name, ts, user, terminal) in + [("valid", 200, true, false), ("orphan", 100, false, true)] + { + let mut call = crate::test_support::make_call(&format!("{name}-{group}"), None, 0, &[]); + let detail = Arc::get_mut(&mut call.call).unwrap(); + detail.source_id = "synthetic-source".into(); + detail.request_time = ts; + detail.response_time = Some(ts + 10); + detail.complete_time = Some(ts + 20); + call.agent.session_id = format!("group-{group}"); + call.agent.is_user_turn_start = Some(user); + call.agent.is_turn_terminal = terminal; + input.send(TurnShardInput::Call(call)).await.unwrap(); + } + } + drop(input); + let mut completed = Vec::new(); + while let Some(turn) = turns.recv().await { + completed.push(turn); + } + for handle in handles { + handle.await.unwrap(); + } + assert_eq!(completed.len(), 64); + assert!(completed + .iter() + .all(|t| t.status == crate::TraceStatus::Incomplete && t.call_count == 1)); + assert!( + registry.read().unwrap().is_empty(), + "EOF replay must leave zero ghost InProgress rows" + ); +} + +#[tokio::test] +async fn longrun_downstream_exit_removes_owned_snapshots() { + let registry = crate::new_active_trace_registry(); + let (input, receiver) = mpsc::channel(4); + let (output, turns) = mpsc::channel(4); + drop(turns); + let mut metrics = MetricsSystem::new(); + let handles = spawn_turn_stage( + TrackerConfig { + grace: std::time::Duration::ZERO, + ..TrackerConfig::default() + }, + vec![receiver], + output, + &mut metrics, + Some(registry.clone()), + ); + let _svc = metrics.start(); + for (session, terminal) in [("pending", false), ("complete", true)] { + let mut call = crate::test_support::make_call(session, None, 0, &[]); + call.agent.session_id = session.into(); + call.agent.is_user_turn_start = Some(true); + call.agent.is_turn_terminal = terminal; + input.send(TurnShardInput::Call(call)).await.unwrap(); + } + for handle in handles { + tokio::time::timeout(std::time::Duration::from_secs(5), handle) + .await + .unwrap() + .unwrap(); + } + assert!( + registry.read().unwrap().is_empty(), + "downstream exit must retire pending snapshots too" + ); +} diff --git a/server/h-turn/src/tracker.rs b/server/h-turn/src/tracker.rs index 29dfcaca..f3f35b83 100644 --- a/server/h-turn/src/tracker.rs +++ b/server/h-turn/src/tracker.rs @@ -6,7 +6,8 @@ //! terminal and every partition becomes one `Trace`. Partitions that //! contain no `is_user_turn_start = Some(true)` call are discarded. -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::net::IpAddr; use std::time::{Duration, Instant}; use uuid::Uuid; @@ -17,17 +18,55 @@ use h_llm::agent_classifier::SuspiciousSignal; use h_llm::model::AgentCall; use crate::model::{ActiveTraceRegistry, Trace, TraceStatus}; +#[cfg(test)] use crate::SuspiciousSkillRollup; +#[cfg(test)] +#[derive(Clone, Copy, Debug, Default)] +struct WorkCounts { + snapshot_visits: usize, + terminal_visits: usize, + session_visits: usize, + final_visits: usize, +} + +#[cfg(test)] +thread_local! { + static WORK_COUNTS: std::cell::Cell = const { std::cell::Cell::new(WorkCounts { + snapshot_visits: 0, terminal_visits: 0, session_visits: 0, final_visits: 0, + }) }; +} + +macro_rules! count_work { + ($field:ident, $count:expr) => { + #[cfg(test)] + WORK_COUNTS.with(|cell| { + let mut counts = cell.get(); + counts.$field += $count; + cell.set(counts); + }); + }; +} + +#[cfg(test)] +fn reset_work() { + WORK_COUNTS.with(|cell| cell.set(WorkCounts::default())); +} + +#[cfg(test)] +fn work() -> WorkCounts { + WORK_COUNTS.with(std::cell::Cell::get) +} + const FINAL_ANSWER_PREVIEW_CHARS: usize = 500; const USER_INPUT_PREVIEW_CHARS: usize = 500; fn truncate_preview(s: &str, max_chars: usize) -> String { - if s.chars().count() <= max_chars { - return s.to_string(); + let mut chars = s.chars(); + let mut out: String = chars.by_ref().take(max_chars).collect(); + if chars.next().is_some() { + out.push('…'); } - let mut out: String = s.chars().take(max_chars).collect(); - out.push('…'); out } @@ -66,76 +105,146 @@ pub enum TurnEvent { Completed(Trace), } +/// Only metadata consumed by turn assembly. Raw bodies and headers remain on +/// the independently owned storage call, rather than living until turn close. +#[derive(Debug)] +struct CallSummary { + source_id: String, + id: String, + wire_api: &'static str, + model: String, + request_time: i64, + response_time: Option, + complete_time: Option, + finish_reason: Option, + input_tokens: Option, + output_tokens: Option, + cache_read_input_tokens: Option, + cache_creation_input_tokens: Option, + client_ip: IpAddr, + server_ip: IpAddr, + has_process: bool, +} + +#[derive(Debug)] +struct AgentSummary { + agent_kind: &'static str, + session_id: String, + subagent_name: Option, + is_user_turn_start: Option, + is_turn_terminal: bool, + /// Already bounded to the same Unicode previews persisted on Trace. + user_input: Option, + assistant_text: Option, + tool_surface: Option, + agent_topology: Option, + tool_call_count: u32, + suspicious_signals: Vec, +} + +#[derive(Debug)] +struct TurnCall { + call: CallSummary, + agent: AgentSummary, +} + +impl From for TurnCall { + fn from(ic: AgentCall) -> Self { + let AgentCall { call, agent } = ic; + Self { + call: CallSummary { + source_id: call.source_id.clone(), + id: call.id.clone(), + wire_api: call.wire_api, + model: call.model.clone(), + request_time: call.request_time, + response_time: call.response_time, + complete_time: call.complete_time, + finish_reason: call.finish_reason.clone(), + input_tokens: call.input_tokens, + output_tokens: call.output_tokens, + cache_read_input_tokens: call.cache_read_input_tokens, + cache_creation_input_tokens: call.cache_creation_input_tokens, + client_ip: call.client_ip, + server_ip: call.server_ip, + has_process: call.process.is_some(), + }, + agent: AgentSummary { + agent_kind: agent.agent_kind, + session_id: agent.session_id, + subagent_name: agent.subagent_name, + is_user_turn_start: agent.is_user_turn_start, + is_turn_terminal: agent.is_turn_terminal, + user_input: agent + .user_input + .map(|text| truncate_preview(&text, USER_INPUT_PREVIEW_CHARS)), + assistant_text: agent + .assistant_text + .map(|text| truncate_preview(&text, FINAL_ANSWER_PREVIEW_CHARS)), + tool_surface: agent.tool_surface, + agent_topology: agent.agent_topology, + tool_call_count: agent.tool_call_count, + suspicious_signals: agent.suspicious_signals, + }, + } + } +} + #[derive(Debug)] struct BufferedCall { - ic: AgentCall, - /// Wall-clock `Instant` at the moment ingest stored this call. Each - /// terminal's grace is checked against its own arrival time **in - /// wall-clock**, not event time — grace measures pipeline fan-in jitter, - /// which is a physical-time phenomenon. - arrived_at_wall: Instant, + ic: TurnCall, /// Cached "this call is a main-agent turn terminator" — i.e. /// `agent.subagent_name.is_none() && agent.is_turn_terminal`. Cached at /// ingest time so finalize doesn't re-compose per element. is_terminal: bool, } +#[path = "tracker_aggregate.rs"] +mod aggregate; +use aggregate::{build_turn, build_turn_with_rollup, TraceRollup}; + +type CallOrder = (i64, u64); +type SessionKey = (String, String); + +#[derive(Default, Debug)] +struct HeadSnapshot { + turn_id: Option, + closed: bool, + rollup: TraceRollup, +} + #[derive(Default, Debug)] struct SessionBuffer { - /// Calls awaiting partition, ordered by `request_time`. The Vec at each - /// key handles request_time collisions in insertion order. - pending: BTreeMap>, - /// `arrived_at_wall` of the earliest pending terminal. `None` ⇒ no - /// terminal currently pending. Set by ingest; reseated by finalize after - /// each partition emission. - grace_started_at_wall: Option, - /// Largest `request_time` ever included in a finalized (or discarded) - /// partition for this session. New arrivals strictly older than this are - /// orphaned at the entry guard. + /// The sequence component preserves insertion order at equal timestamps. + pending: BTreeMap, + next_sequence: u64, + /// Ordered independently of arrival time: only the first terminal can close. + terminals: BTreeMap, last_finalized_request_time: Option, - /// Latest per-source `virtual_now` observed for this buffer, in - /// event-time µs. Used as the idle reference by `sweep` / `gc_buffers`. last_activity_us: i64, - /// Stable `turn_id` for the in-progress turn currently assembling in - /// this buffer. Minted lazily on the first ingest after the previous - /// turn was finalized; reused by every snapshot inserted into the - /// `ActiveTraceRegistry` and by the eventual `Completed` turn so the - /// in-memory in-progress entry's id matches the row that gets - /// persisted (lets the API drop the registry entry without a - /// frontend "row jump"). Cleared on every finalize / sweep / flush. - current_turn_id: Option, + /// IDs belong to a call actually represented by their snapshot. An earlier + /// out-of-order terminal may hide a snapshot without consuming its ID. + turn_ids: BTreeMap, + head: Option, + grace_deadline: Option, + idle_activity: Option, + gc_activity: Option, } -/// Single stateful owner of turn assembly. Passive: callers drive it via -/// `ingest`, `advance_time`, `sweep`, `flush_all`. -/// -/// Pure assembly stage: classification (`is_turn_terminal`, `is_user_turn_start`, -/// `subagent_name`, `is_auxiliary`, `user_input`, `assistant_text`) is decided -/// once at the h-llm boundary and carried on `AgentCall.agent`. The tracker -/// only reads those fields — no profile or wire-api registry held here. -/// "Main-agent terminal" is composed at read sites as -/// `agent.subagent_name.is_none() && agent.is_turn_terminal`. -/// -/// Two clocks by design: -/// * `virtual_now_by_source` — per-source event-time watermark. Bumped by -/// each source's own heartbeats and ingested calls. Used for idle sweep, -/// gc, and the orphan guard. Per-source so one source's activity cannot -/// fast-forward another source's idle/gc horizon. -/// * `Instant` taken at ingest / advance — wall-clock. Used only for grace. +/// Stateful turn assembly with per-source event-time idle clocks and a +/// wall-clock grace budget. Callers drive ingest, heartbeat, sweep and drain. pub struct TurnTracker { config: TrackerConfig, - buffers: HashMap<(String, String), SessionBuffer>, - /// Event-time watermark, keyed by `source_id`. `0` ≡ "never seen". + buffers: HashMap, + pending_count: usize, virtual_now_by_source: HashMap, - /// Global sweep-interval throttle, in event-time µs. Not per-source — it - /// only controls how often `sweep` iterates buffers, not correctness. + global_virtual_now: i64, + dirty_sources: HashSet, last_sweep_us: i64, + grace_deadlines: BTreeSet<(Instant, SessionKey)>, + idle_by_source: HashMap>, + gc_by_source: HashMap>, metrics: MetricsWorker, - /// Optional in-memory registry of in-progress turns, shared between - /// every tracker and the API handler. When present, every `ingest_at` - /// upserts a snapshot into the registry, and every finalize / - /// sweep / flush removes the entry. `None` is used by tests that - /// don't care about the snapshot path. active_registry: Option, } @@ -144,10 +253,7 @@ impl TurnTracker { Self::with_registry(config, metrics, None) } - /// Variant that wires an [`ActiveTraceRegistry`] into the tracker so - /// the API can read in-progress snapshots without going through the - /// DB or a channel fan-out. Pipelines call this; tests that don't - /// exercise the snapshot path use [`Self::new`]. + /// Share in-progress snapshots with the API without persisting each update. pub fn with_registry( config: TrackerConfig, metrics: MetricsWorker, @@ -156,42 +262,40 @@ impl TurnTracker { Self { config, buffers: HashMap::new(), + pending_count: 0, virtual_now_by_source: HashMap::new(), + global_virtual_now: 0, + dirty_sources: HashSet::new(), last_sweep_us: 0, + grace_deadlines: BTreeSet::new(), + idle_by_source: HashMap::new(), + gc_by_source: HashMap::new(), metrics, active_registry, } } - /// Total pending calls across every buffer. + /// Total pending calls, also used after every stage input for the gauge. pub fn active_count(&self) -> usize { - self.buffers - .values() - .map(|b| b.pending.values().map(|v| v.len()).sum::()) - .sum() + self.pending_count } - /// Bump the per-source event-time watermark to `max(current, ts)` and - /// return the new value. fn bump_event_time(&mut self, source_id: &str, ts: i64) -> i64 { - let e = self + let watermark = self .virtual_now_by_source .entry(source_id.to_string()) .or_insert(0); - *e = (*e).max(ts); - *e + *watermark = (*watermark).max(ts); + self.global_virtual_now = self.global_virtual_now.max(*watermark); + self.dirty_sources.insert(source_id.to_string()); + *watermark } - /// Ingest one agent-attributed, completed call using the current wall-clock. pub fn ingest(&mut self, ic: AgentCall) -> Vec { self.ingest_at(ic, Instant::now()) } - /// Ingest with an injectable wall-clock (tests). - /// - /// Event-time watermark is bumped on the **call's own `source_id`** only; - /// grace timestamps are wall-clock. Together this ensures that no activity - /// outside this `(source_id, session_id)` can shrink its grace window. + /// Injectable wall-clock; event-time advances only for the call's source. pub fn ingest_at(&mut self, ic: AgentCall, now_wall: Instant) -> Vec { let arrival_ts = ic .call @@ -199,224 +303,165 @@ impl TurnTracker { .or(ic.call.response_time) .unwrap_or(ic.call.request_time); let source_id = ic.call.source_id.clone(); - let session_id = ic.agent.session_id.clone(); let virtual_now = self.bump_event_time(&source_id, arrival_ts); self.metrics.counter(Metric::TurnCallsIngested).inc(); - - // Auxiliary one-shots (e.g., claude-cli session-title) bypass turn - // assembly entirely. They still flow to storage independently. if ic.agent.is_auxiliary { self.metrics.counter(Metric::TurnCallsAuxiliary).inc(); - return self.flush_ready_buffers(now_wall); - } - - let key = (source_id.clone(), session_id.clone()); - let buf = self.buffers.entry(key).or_default(); - - if let Some(hw) = buf.last_finalized_request_time { - if ic.call.request_time < hw { + } else { + let key = (source_id.clone(), ic.agent.session_id.clone()); + let buf = self.buffers.entry(key.clone()).or_default(); + if buf + .last_finalized_request_time + .is_some_and(|hw| ic.call.request_time < hw) + { self.metrics.counter(Metric::TurnCallsDroppedLate).inc(); - return self.flush_ready_buffers(now_wall); + } else { + let order = (ic.call.request_time, buf.next_sequence); + buf.next_sequence += 1; + let ordered = buf + .pending + .last_key_value() + .is_none_or(|(last, _)| *last < order); + let is_terminal = ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal; + if is_terminal { + buf.terminals.insert(order, now_wall); + } + buf.pending.insert( + order, + BufferedCall { + ic: ic.into(), + is_terminal, + }, + ); + buf.last_activity_us = virtual_now; + self.pending_count += 1; + if let Some(registry) = &self.active_registry { + append_active_snapshot(&key, buf, order, ordered, registry); + } + self.reindex(&key); } } - - // Main-agent terminal = sub-agent layering filter ANDed with the raw - // protocol-terminal verdict from h-llm. Same composition pattern as - // the user-start check in `emit_or_discard`. - let is_terminal = ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal; - let request_time = ic.call.request_time; - buf.pending - .entry(request_time) - .or_default() - .push(BufferedCall { - ic, - arrived_at_wall: now_wall, - is_terminal, - }); - buf.last_activity_us = virtual_now; - if is_terminal && buf.grace_started_at_wall.is_none() { - buf.grace_started_at_wall = Some(now_wall); - } - - // Mint a stable `turn_id` for this in-progress turn the first time we - // see a call after the previous turn finalized. Reused by every - // registry snapshot AND by the eventual persisted `Completed`, so the - // `agent_turns` row's `turn_id` matches the in-progress entry the - // console has been showing. Cleared by `emit_or_discard` after - // finalize so the next ingest mints a fresh one. - if buf.current_turn_id.is_none() { - buf.current_turn_id = Some(Uuid::now_v7().to_string()); - } - - // Refresh the registry's snapshot for this turn. Cheap (one HashMap - // upsert + an Trace alloc); skipped if no registry is wired (e.g. - // tests via `TurnTracker::new`). - self.refresh_active_snapshot(&source_id, &session_id); - - self.flush_ready_buffers(now_wall) + let events = self.flush_ready_buffers(now_wall); + self.gc_buffers(&source_id); + events } - /// Build the in-progress Trace snapshot for a given session and - /// upsert it into the active registry. Truncates the partition at the - /// first main-agent terminal so multi-turn buffers don't mix two - /// turns' state into one snapshot. Applies the same discard rule as - /// `emit_or_discard` so we don't leak phantom in-progress rows for - /// sub-agent-only filler sessions. - fn refresh_active_snapshot(&self, source_id: &str, session_id: &str) { - let registry = match &self.active_registry { - Some(r) => r, - None => return, - }; - let buf = match self + /// Each buffer has at most one entry in each relevant deadline index. + /// Remove replaced entries rather than accumulating stale heap nodes. + fn reindex(&mut self, key: &SessionKey) { + let buf = self .buffers - .get(&(source_id.to_string(), session_id.to_string())) - { - Some(b) => b, - None => return, - }; - let turn_id = match &buf.current_turn_id { - Some(id) => id.clone(), - None => return, - }; - - // Partition: calls up to and including the first main-agent terminal. - let partition: Vec<&AgentCall> = { - let mut sorted: Vec<&BufferedCall> = buf.pending.values().flatten().collect(); - sorted.sort_by_key(|bc| bc.ic.call.request_time); - let mut acc: Vec<&AgentCall> = Vec::with_capacity(sorted.len()); - for bc in sorted { - acc.push(&bc.ic); - if bc.is_terminal { - break; - } + .get_mut(key) + .expect("buffer exists while indexing"); + let grace = buf + .terminals + .first_key_value() + .and_then(|(_, arrived)| arrived.checked_add(self.config.grace)); + if grace != buf.grace_deadline { + if let Some(old) = buf.grace_deadline.take() { + self.grace_deadlines.remove(&(old, key.clone())); } - acc - }; - if partition.is_empty() { - return; + if let Some(deadline) = grace { + self.grace_deadlines.insert((deadline, key.clone())); + } + buf.grace_deadline = grace; } - // Same discard rule as emit_or_discard — only show in-progress rows - // whose partition has a main-agent user_turn_start, OR (PID fallback) - // whose calls share eBPF process attribution when the turn's opening - // call was missed. Without this, a sub-agent dispatch's first call - // (which carries `is_user_turn_start=Some(true)` AND - // `subagent_name=Some(_)`) would produce a phantom row that finalize - // will eventually drop — the sub-agent guard in both predicates still - // filters those out. Metric is bumped only at finalize (emit_or_discard), - // not here — this refresh runs on every ingest and would double-count. - let has_user_start = partition.iter().any(|ic| main_agent_user_turn_start(ic)); - let kept_by_pid = - !has_user_start && partition_has_pid_attribution(partition.iter().copied()); - if !(has_user_start || kept_by_pid) { - return; + let idle = + (!buf.pending.is_empty() && buf.terminals.is_empty()).then_some(buf.last_activity_us); + if idle != buf.idle_activity { + // Grace may expose an already-idle tail while another source is + // driving this mutation. Reconsider its unchanged watermark too. + self.dirty_sources.insert(key.0.clone()); + let index = self.idle_by_source.entry(key.0.clone()).or_default(); + if let Some(old) = buf.idle_activity.take() { + index.remove(&(old, key.1.clone())); + } + if let Some(activity) = idle { + index.insert((activity, key.1.clone())); + } + buf.idle_activity = idle; } - - let mut snap = build_turn( - &partition, - Some(turn_id.clone()), - Some(TraceStatus::InProgress), - ); - snap.source_id = source_id.to_string(); - snap.session_id = session_id.to_string(); - - if let Ok(mut map) = registry.write() { - map.insert(turn_id, snap); + let gc = (buf.pending.is_empty() && buf.last_finalized_request_time.is_some()) + .then_some(buf.last_activity_us); + if gc != buf.gc_activity { + let index = self.gc_by_source.entry(key.0.clone()).or_default(); + if let Some(old) = buf.gc_activity.take() { + index.remove(&(old, key.1.clone())); + } + if let Some(activity) = gc { + index.insert((activity, key.1.clone())); + } + buf.gc_activity = gc; } } - /// Read-side helper used by tests to inspect the registry contents - /// without going through the lock directly. Returns a clone of every - /// in-progress snapshot currently registered. Production reads happen - /// in `h-api` directly against the `ActiveTraceRegistry` Arc. + /// Registry reads are cloned only at the read boundary, never on append. pub fn snapshot_active(&self) -> Vec { - match &self.active_registry { - Some(reg) => reg - .read() - .map(|map| map.values().cloned().collect()) - .unwrap_or_default(), - None => Vec::new(), - } + self.active_registry + .as_ref() + .and_then(|reg| reg.read().ok().map(|map| map.values().cloned().collect())) + .unwrap_or_default() } - /// Walk every buffer; for each whose front-pending terminal's grace has - /// expired (by wall-clock), hand off to `finalize_session` to emit one or - /// more turns. fn flush_ready_buffers(&mut self, now_wall: Instant) -> Vec { - let grace = self.config.grace; - - let ready_keys: Vec<(String, String)> = self - .buffers - .iter() - .filter_map(|(k, b)| match b.grace_started_at_wall { - Some(started) if now_wall.duration_since(started) >= grace => Some(k.clone()), - _ => None, - }) - .collect(); - let mut events = Vec::new(); - for key in ready_keys { - let buf = self.buffers.get_mut(&key).expect("key just listed"); - finalize_session( - &key.0, - &key.1, + while self + .grace_deadlines + .first() + .is_some_and(|(deadline, _)| *deadline <= now_wall) + { + let (_, key) = self + .grace_deadlines + .pop_first() + .expect("deadline just observed"); + count_work!(session_visits, 1); + let buf = self.buffers.get_mut(&key).expect("indexed buffer exists"); + buf.grace_deadline = None; + self.pending_count -= finalize_session( + &key, buf, now_wall, - grace, + self.config.grace, + false, &self.metrics, + self.active_registry.as_ref(), &mut events, ); + // A heartbeat may be the last input: publish the tail right here. + if let Some(registry) = &self.active_registry { + rebuild_active_snapshot(&key, buf, registry); + } + self.reindex(&key); + self.gc_buffers(&key.0); } - self.gc_buffers(); - self.drop_completed_from_registry(&events); events } - /// After any Completed turn is emitted, drop its in-progress entry - /// from the registry — the persisted DB row replaces it in the API's - /// UNION view, so leaving the snapshot would double-count. Idempotent; - /// safe to call with stacked-partition turn_ids that were never in - /// the registry. - fn drop_completed_from_registry(&self, events: &[TurnEvent]) { - let registry = match &self.active_registry { - Some(r) => r, - None => return, - }; - let mut map = match registry.write() { - Ok(g) => g, - Err(_) => return, + /// Only empty buffers on a source whose watermark moved can become old. + fn gc_buffers(&mut self, source_id: &str) { + let watermark = self + .virtual_now_by_source + .get(source_id) + .copied() + .unwrap_or(0); + let cutoff = watermark.saturating_sub(self.config.idle_timeout_us.saturating_mul(2)); + let Some(index) = self.gc_by_source.get_mut(source_id) else { + return; }; - for ev in events { - let TurnEvent::Completed(t) = ev; - map.remove(&t.turn_id); + while index + .first() + .is_some_and(|(activity, _)| *activity < cutoff) + { + let (_, session) = index.pop_first().expect("entry just observed"); + count_work!(session_visits, 1); + self.buffers.remove(&(source_id.to_string(), session)); } } - /// Drop fully-drained buffers whose `last_activity_us` is well past the - /// idle horizon (measured against **their own source's** virtual_now, so - /// a quiet source's old buffers aren't gc'd because another source has - /// moved on). Past `2 × idle_timeout_us` we lose the orphan guard for - /// that session — far longer than any plausible reorder. - fn gc_buffers(&mut self) { - let cfg_idle = self.config.idle_timeout_us; - let vn_by_source = &self.virtual_now_by_source; - self.buffers.retain(|(source_id, _), b| { - let vn = vn_by_source.get(source_id).copied().unwrap_or(0); - let cutoff = vn.saturating_sub(2 * cfg_idle); - !(b.pending.is_empty() - && b.last_finalized_request_time.is_some() - && b.last_activity_us < cutoff) - }); - } - - /// Advance virtual time using a heartbeat forwarded through the pipeline. - /// Bumps only the event-time watermark of **this source**; grace is - /// evaluated against wall-clock, so a busy source cannot fast-forward a - /// quiet source's grace window. pub fn advance_time(&mut self, ts: i64, source_id: &str) -> Vec { self.advance_time_at(ts, source_id, Instant::now()) } - /// Same as [`advance_time`], with an injectable wall-clock (tests). pub fn advance_time_at( &mut self, ts: i64, @@ -426,255 +471,299 @@ impl TurnTracker { self.metrics.counter(Metric::TurnHeartbeatsReceived).inc(); self.bump_event_time(source_id, ts); let mut events = self.flush_ready_buffers(now_wall); - // Sweep is pure event-time logic — no wall-clock variant needed. + self.gc_buffers(source_id); events.extend(self.sweep()); events } - /// Idle fallback: drain buffers that hold no terminal call and whose - /// newest call is older than `idle_timeout_us` in their own source's - /// event-time. Discard rule applies. - /// - /// Event-time only — no wall-clock input. Callers with a wall-clock in - /// hand (test-driven `advance_time_at`) don't need an `_at` variant - /// because sweep never consults wall-clock. + /// Preserve the global sweep throttle; inspect only changed sources and + /// idle deadlines that can actually expire under each source's own clock. pub fn sweep(&mut self) -> Vec { - // Throttle: use the max across all per-source watermarks. sweep only - // runs at most once per `sweep_interval_us` of global progress — this - // is a coarse rate limiter, not a correctness-critical clock. - let global_virtual_now = self - .virtual_now_by_source - .values() - .copied() - .max() - .unwrap_or(0); - if global_virtual_now - self.last_sweep_us < self.config.sweep_interval_us { + if self.global_virtual_now - self.last_sweep_us < self.config.sweep_interval_us { return Vec::new(); } - self.last_sweep_us = global_virtual_now; - let cfg_idle = self.config.idle_timeout_us; - - let candidates: Vec<(String, String)> = { - let vn_by_source = &self.virtual_now_by_source; - self.buffers - .iter() - .filter(|((source_id, _), b)| { - let vn = vn_by_source.get(source_id).copied().unwrap_or(0); - !b.pending.is_empty() - && !b.pending.values().flatten().any(|bc| bc.is_terminal) - && b.last_activity_us < vn - cfg_idle - }) - .map(|(k, _)| k.clone()) - .collect() - }; - + self.last_sweep_us = self.global_virtual_now; + let sources: Vec = self.dirty_sources.drain().collect(); let mut events = Vec::new(); - for key in candidates { - let buf = match self.buffers.get_mut(&key) { - Some(b) => b, - None => continue, - }; - let drained: Vec = std::mem::take(&mut buf.pending) - .into_values() - .flatten() - .collect(); - if drained.is_empty() { - continue; + for source in sources { + let watermark = self + .virtual_now_by_source + .get(&source) + .copied() + .unwrap_or(0); + let cutoff = watermark - self.config.idle_timeout_us; + loop { + let candidate = self.idle_by_source.get_mut(&source).and_then(|index| { + if index + .first() + .is_some_and(|(activity, _)| *activity < cutoff) + { + index.pop_first() + } else { + None + } + }); + let Some((_, session)) = candidate else { + break; + }; + count_work!(session_visits, 1); + let key = (source.clone(), session); + let buf = self.buffers.get_mut(&key).expect("indexed buffer exists"); + buf.idle_activity = None; + self.pending_count -= drain_tail( + &key, + buf, + &self.metrics, + self.active_registry.as_ref(), + &mut events, + FinalizeKind::Idle, + ); + self.reindex(&key); } - let max_request_time = drained - .iter() - .map(|bc| bc.ic.call.request_time) - .max() - .expect("non-empty"); - buf.last_finalized_request_time = Some(max_request_time); - buf.grace_started_at_wall = None; - // Reuse the in-progress turn_id so the persisted Incomplete - // turn shares the same id the registry has been advertising. - // The registry entry will be dropped at the end of this fn. - let turn_id_override = buf.current_turn_id.take(); - - // sweep already counts itself via FinalizeKind::Idle inside - // emit_or_discard; the returned bool isn't needed here. - let _ = emit_or_discard( - &key.0, - &key.1, - &drained, - turn_id_override, - &self.metrics, - &mut events, - FinalizeKind::Idle, - ); + self.gc_buffers(&source); } - self.gc_buffers(); - self.drop_completed_from_registry(&events); events } - /// EOF / shutdown drain using the current wall-clock. pub fn flush_all(&mut self) -> Vec { self.flush_all_at(Instant::now()) } - /// EOF / shutdown drain with an injectable wall-clock (tests). Force - /// every pending terminal past its grace, then emit any remaining - /// non-terminal tail (subject to discard rule). + /// EOF forces terminal partitions past grace, then drains incomplete tails. pub fn flush_all_at(&mut self, now_wall: Instant) -> Vec { - let mut keys: Vec<(String, String)> = self.buffers.keys().cloned().collect(); + let mut keys: Vec = self.buffers.keys().cloned().collect(); keys.sort(); - // Force all terminals past their grace by advancing wall-clock beyond - // any pending terminal's arrival + grace. `grace + 1ns` off now_wall - // is enough because new arrivals at/after `now_wall` can't be in the - // buffer yet. - let force_wall = now_wall - .checked_add(self.config.grace) - .and_then(|t| t.checked_add(Duration::from_nanos(1))) - .unwrap_or(now_wall); - let grace = self.config.grace; - let mut events = Vec::new(); for key in keys { - // Step 1: drive the terminal-bounded partitions to finalize. - { - let buf = self.buffers.get_mut(&key).expect("listed above"); - finalize_session( - &key.0, - &key.1, - buf, - force_wall, - grace, - &self.metrics, - &mut events, - ); - } - // Step 2: drain any non-terminal tail as Incomplete (or discard). - let buf = self.buffers.get_mut(&key).expect("listed above"); - let drained: Vec = std::mem::take(&mut buf.pending) - .into_values() - .flatten() - .collect(); - if drained.is_empty() { - continue; - } - let max_request_time = drained - .iter() - .map(|bc| bc.ic.call.request_time) - .max() - .expect("non-empty"); - buf.last_finalized_request_time = Some(max_request_time); - buf.grace_started_at_wall = None; - // Step 1's finalize_session may already have consumed - // current_turn_id; if any non-terminal tail is still here it - // belongs to a turn that the shutdown caught mid-flight. Reuse - // the id when present so the API's UNION view doesn't briefly - // show two rows (in-progress + Incomplete) for the same turn. - let turn_id_override = buf.current_turn_id.take(); - // flush_all's non-terminal tail doesn't have a dedicated counter - // beyond TurnsCompleted (bumped inside emit_or_discard). - let _ = emit_or_discard( - &key.0, - &key.1, - &drained, - turn_id_override, + let buf = self.buffers.get_mut(&key).expect("listed buffer exists"); + self.pending_count -= finalize_session( + &key, + buf, + now_wall, + self.config.grace, + true, + &self.metrics, + self.active_registry.as_ref(), + &mut events, + ); + self.pending_count -= drain_tail( + &key, + buf, &self.metrics, + self.active_registry.as_ref(), &mut events, FinalizeKind::Flush, ); + self.reindex(&key); } - self.drop_completed_from_registry(&events); events } } -#[derive(Copy, Clone)] -enum FinalizeKind { - Idle, - Flush, +impl Drop for TurnTracker { + fn drop(&mut self) { + if let Some(registry) = &self.active_registry { + if let Ok(mut map) = registry.write() { + for buf in self.buffers.values() { + for id in buf.turn_ids.values() { + map.remove(id); + } + } + } + } + } } -/// Loop-emit one turn per pending main-agent terminal whose own grace has -/// expired, partitioning at each terminal's `request_time`. Stops as soon -/// as the next pending terminal still sits inside its grace window, and -/// reseats `buf.grace_started_at_wall` to that next terminal's arrival. -fn finalize_session( - source_id: &str, - session_id: &str, +fn append_active_snapshot( + key: &SessionKey, buf: &mut SessionBuffer, - now_wall: Instant, - grace: Duration, - metrics: &MetricsWorker, - events: &mut Vec, + order: CallOrder, + ordered: bool, + registry: &ActiveTraceRegistry, ) { - loop { - let mut sorted: Vec<&BufferedCall> = buf.pending.values().flatten().collect(); - sorted.sort_by_key(|bc| bc.ic.call.request_time); - if sorted.is_empty() { - buf.grace_started_at_wall = None; - return; + if ordered { + if let Some(head) = &mut buf.head { + // Ordered tail calls cannot change a terminal-bounded head. + if head.closed { + return; + } + let call = &buf.pending.get(&order).expect("new call exists").ic; + count_work!(snapshot_visits, 1); + if let Some(id) = &head.turn_id { + if let Ok(mut map) = registry.write() { + if let Some(trace) = map.get_mut(id) { + head.rollup.append(trace, call); + trace.status = TraceStatus::InProgress; + head.closed = + call.agent.subagent_name.is_none() && call.agent.is_turn_terminal; + return; + } + } + } else { + head.rollup.observe_eligibility(call); + head.closed = call.agent.subagent_name.is_none() && call.agent.is_turn_terminal; + if !head.rollup.eligible() { + return; + } + } } + } + rebuild_active_snapshot(key, buf, registry); +} - let terminal_idx = sorted.iter().position(|bc| bc.is_terminal); - let idx = match terminal_idx { +fn rebuild_active_snapshot( + key: &SessionKey, + buf: &mut SessionBuffer, + registry: &ActiveTraceRegistry, +) { + let old_id = buf.head.take().and_then(|head| head.turn_id); + let mut head = HeadSnapshot::default(); + let mut calls = Vec::new(); + let mut last_order = None; + let mut eligibility_anchor = None; + for (order, call) in &buf.pending { + calls.push(&call.ic); + last_order = Some(*order); + head.rollup.observe_eligibility(&call.ic); + if eligibility_anchor.is_none() && head.rollup.eligible() { + eligibility_anchor = Some(*order); + } + if call.is_terminal { + head.closed = true; + break; + } + } + count_work!(snapshot_visits, calls.len()); + let mut snapshot = None; + if head.rollup.eligible() { + let end = last_order.expect("eligible head is nonempty"); + let id = match buf.turn_ids.range(..=end).next() { + Some((_, id)) => id.clone(), None => { - buf.grace_started_at_wall = None; - return; + let id = Uuid::now_v7().to_string(); + // An ineligible prefix may later be discarded independently; + // reserve the ID at the call that made this head eligible. + buf.turn_ids.insert( + eligibility_anchor.expect("eligible head has an eligibility-bearing call"), + id.clone(), + ); + id } - Some(i) => i, }; - let front_arrived = sorted[idx].arrived_at_wall; - if now_wall.duration_since(front_arrived) < grace { - // Reseat grace clock to *this* terminal's arrival — earlier - // terminals may already have been consumed in prior iterations. - buf.grace_started_at_wall = Some(front_arrived); - return; + let (mut trace, rollup) = + build_turn_with_rollup(&calls, Some(id.clone()), Some(TraceStatus::InProgress)); + trace.source_id = key.0.clone(); + trace.session_id = key.1.clone(); + head.rollup = rollup; + head.turn_id = Some(id); + snapshot = Some(trace); + } + if let Ok(mut map) = registry.write() { + if let Some(id) = old_id { + map.remove(&id); } + if let Some(trace) = snapshot { + map.insert(trace.turn_id.clone(), trace); + } + } + if !calls.is_empty() { + buf.head = Some(head); + } +} + +#[derive(Copy, Clone)] +enum FinalizeKind { + Idle, + Flush, +} - let terminal_ts = sorted[idx].ic.call.request_time; - // Partition: every pending key ≤ terminal_ts → this turn. - let turn_keys: Vec = buf.pending.range(..=terminal_ts).map(|(k, _)| *k).collect(); - let mut turn_calls: Vec = Vec::new(); - for k in turn_keys { - if let Some(v) = buf.pending.remove(&k) { - turn_calls.extend(v); +/// Retire IDs on partition removal, including discarded partitions. IDs whose +/// anchors are in a later partition remain reserved (but may be hidden). +fn retire_partition_ids( + buf: &mut SessionBuffer, + boundary: CallOrder, + registry: Option<&ActiveTraceRegistry>, +) -> Option { + let remaining = buf.turn_ids.split_off(&boundary); + let retired = std::mem::replace(&mut buf.turn_ids, remaining); + buf.head = None; + if let Some(registry) = registry { + if let Ok(mut map) = registry.write() { + for id in retired.values() { + map.remove(id); } } + } + retired.into_values().next() +} - // `emit_or_discard` returns whether this partition actually produced - // a Completed event; the discard rule can drop partitions with no - // user_turn_start. We must NOT inspect `events.last()` here because - // the loop may have already pushed a Completed in a previous - // iteration, which would falsely bump the grace counter for a - // discarded partition. - // - // First pass through the loop: hand the buffer's in-progress - // current_turn_id to emit_or_discard so the persisted Completed - // shares the id with the active-registry snapshot. Subsequent - // partitions in the same buffer are independent turns that never - // had an in-progress entry, so they get fresh UUIDs (None → - // build_turn mints). - let turn_id_override = buf.current_turn_id.take(); - let emitted = emit_or_discard( - source_id, - session_id, - &turn_calls, - turn_id_override, +fn finalize_session( + key: &SessionKey, + buf: &mut SessionBuffer, + now_wall: Instant, + grace: Duration, + force: bool, + metrics: &MetricsWorker, + registry: Option<&ActiveTraceRegistry>, + events: &mut Vec, +) -> usize { + let mut drained_count = 0; + while let Some((&(terminal_ts, _), &arrived)) = buf.terminals.first_key_value() { + count_work!(terminal_visits, 1); + if !force && now_wall.saturating_duration_since(arrived) < grace { + break; + } + // Keep existing timestamp-bucket finalization semantics, including all + // equal-timestamp calls in their stable insertion order. + let boundary = (terminal_ts, u64::MAX); + let remaining = buf.pending.split_off(&boundary); + let drained: Vec = std::mem::replace(&mut buf.pending, remaining) + .into_values() + .collect(); + buf.terminals = buf.terminals.split_off(&boundary); + drained_count += drained.len(); + let id = retire_partition_ids(buf, boundary, registry); + if emit_or_discard( + &key.0, + &key.1, + &drained, + id, metrics, events, - FinalizeKind::Flush, // grace-driven; only bump grace counter if actually emitted - ); - if emitted { + FinalizeKind::Flush, + ) { metrics.counter(Metric::TurnClosedByGrace).inc(); } - buf.last_finalized_request_time = Some(terminal_ts); - // Loop: the next iteration recomputes the next pending terminal. } + drained_count +} + +fn drain_tail( + key: &SessionKey, + buf: &mut SessionBuffer, + metrics: &MetricsWorker, + registry: Option<&ActiveTraceRegistry>, + events: &mut Vec, + kind: FinalizeKind, +) -> usize { + if buf.pending.is_empty() { + return 0; + } + let max_time = buf.pending.last_key_value().expect("nonempty").0 .0; + let drained: Vec = std::mem::take(&mut buf.pending).into_values().collect(); + buf.terminals.clear(); + buf.last_finalized_request_time = Some(max_time); + let id = retire_partition_ids(buf, (i64::MAX, u64::MAX), registry); + let _ = emit_or_discard(&key.0, &key.1, &drained, id, metrics, events, kind); + drained.len() } /// A main-agent call that opens a user turn: `is_user_turn_start == Some(true)` /// AND not a sub-agent. The sub-agent guard prevents a sub-agent dispatch /// (whose body looks like a fresh user message) from satisfying a partition's /// "needs a main-agent user start" requirement on its own. -fn main_agent_user_turn_start(ic: &AgentCall) -> bool { +fn main_agent_user_turn_start(ic: &TurnCall) -> bool { ic.agent.subagent_name.is_none() && ic.agent.is_user_turn_start == Some(true) } @@ -687,11 +776,11 @@ fn main_agent_user_turn_start(ic: &AgentCall) -> bool { /// must still be dropped even if the calls happen to carry a PID. fn partition_has_pid_attribution<'a, I>(calls: I) -> bool where - I: IntoIterator, + I: IntoIterator, { calls .into_iter() - .any(|ic| ic.agent.subagent_name.is_none() && ic.call.process.is_some()) + .any(|ic| ic.agent.subagent_name.is_none() && ic.call.has_process) } /// Apply the discard rule and emit (or count-and-drop) one turn per drained @@ -727,10 +816,8 @@ fn emit_or_discard( // `is_user_turn_start=Some(true)` *and* `subagent_name=Some(_)`; without // the sub-agent guard here those would slip through and produce phantom // "Incomplete with user_input=None" turns. - let refs: Vec<&AgentCall> = calls.iter().map(|bc| &bc.ic).collect(); - let has_user_start = refs - .iter() - .any(|ic| main_agent_user_turn_start(ic)); + let refs: Vec<&TurnCall> = calls.iter().map(|bc| &bc.ic).collect(); + let has_user_start = refs.iter().any(|ic| main_agent_user_turn_start(ic)); // PID fallback: when no main-agent user-turn-start survived into this // partition (typically because the eBPF source missed the turn's opening // call — the only call whose `messages[-1]` is user text rather than a @@ -749,6 +836,7 @@ fn emit_or_discard( return false; } + count_work!(final_visits, refs.len()); let mut turn = build_turn(&refs, turn_id_override, None); // The buffer key is authoritative for source/session — call.source_id // can legitimately be empty in tests; identity.session_id may differ @@ -763,237 +851,18 @@ fn emit_or_discard( true } -fn push_unique(list: &mut Vec, value: String) { - if !list.iter().any(|v| v == &value) { - list.push(value); - } -} - -/// Pure constructor over a request_time-sorted partition. -/// -/// `turn_id_override`: caller-supplied id. Used by the in-progress -/// snapshot path so every snapshot for the same in-flight turn shares -/// one id, and the eventual finalized `Trace` carries the same id -/// the registry has been advertising. `None` mints a fresh UUID. -/// -/// `status_override`: forces a status. Used by the in-progress snapshot -/// path to pin `InProgress` even when the partition's terminal call has -/// already landed (which can happen briefly during the grace window — -/// the user shouldn't see the row flip via a snapshot; that transition -/// belongs to the persisted Completed). `None` falls back to derived -/// status (Complete iff a main-agent terminal is in the partition; -/// Incomplete otherwise). -/// -/// Turn status and `final_*` are both derived from the composed main-agent -/// terminal pick — `agent.subagent_name.is_none() && agent.is_turn_terminal`, -/// where the protocol-terminal field is set at h-llm time. Profiles whose -/// wire-level `finish_reason` cannot distinguish "final answer" from "tool -/// roundtrip pending" (e.g. codex-cli over openai-responses, where every -/// successful call reports `response.completed`) override -/// `AgentProfile::is_turn_terminal` to inspect the body explicitly; the -/// canonical decision lives upstream. For partitions drained via idle-sweep -/// / EOF-flush with no terminal in the buffer, `final_*` stay `None` and -/// status falls to `Incomplete`. -fn build_turn( - calls: &[&AgentCall], - turn_id_override: Option, - status_override: Option, -) -> Trace { - assert!(!calls.is_empty(), "build_turn requires at least one call"); - let first = calls[0]; - let source_id = first.call.source_id.clone(); - let session_id = first.agent.session_id.clone(); - let agent_kind = first.agent.agent_kind.to_string(); - let wire_api = first.call.wire_api.to_string(); - let client_ip = first.call.client_ip; - let server_ip = first.call.server_ip; - let turn_id = turn_id_override.unwrap_or_else(|| Uuid::now_v7().to_string()); - - let start_time_us = first.call.request_time; - let end_time_us = calls - .iter() - .map(|ic| { - ic.call - .complete_time - .or(ic.call.response_time) - .unwrap_or(ic.call.request_time) - }) - .max() - .expect("non-empty"); - let duration_ms = ((end_time_us - start_time_us).max(0) / 1000) as u64; - - let call_count = calls.len() as u32; - let span_ids: Vec = calls.iter().map(|ic| ic.call.id.clone()).collect(); - - let mut models_used: Vec = Vec::new(); - let mut subagents_used: Vec = Vec::new(); - let mut total_input_tokens: u64 = 0; - let mut total_output_tokens: u64 = 0; - let mut total_cache_read_input_tokens: u64 = 0; - let mut total_cache_creation_input_tokens: u64 = 0; - for ic in calls { - push_unique(&mut models_used, ic.call.model.clone()); - if let Some(sa) = ic.agent.subagent_name.as_ref() { - push_unique(&mut subagents_used, sa.clone()); - } - if let Some(t) = ic.call.input_tokens { - total_input_tokens += t as u64; - } - if let Some(t) = ic.call.output_tokens { - total_output_tokens += t as u64; - } - if let Some(t) = ic.call.cache_read_input_tokens { - total_cache_read_input_tokens += t as u64; - } - if let Some(t) = ic.call.cache_creation_input_tokens { - total_cache_creation_input_tokens += t as u64; - } - } - - // user_input: prefer the main-agent call flagged as user-turn-start. - // Fall back to any main-agent call whose body yielded user_input upstream. - let user_pick = calls - .iter() - .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_user_turn_start == Some(true)) - .or_else(|| { - calls - .iter() - .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.user_input.is_some()) - }); - let (user_input_preview, user_call_id) = match user_pick { - Some(ic) => match ic.agent.user_input.as_deref() { - Some(text) => ( - Some(truncate_preview(text, USER_INPUT_PREVIEW_CHARS)), - Some(ic.call.id.clone()), - ), - None => (None, None), - }, - None => (None, None), - }; - - // Terminal pick: the main-agent call that actually closed this turn. - // Drives both `status` and `final_*`. `None` → turn is Incomplete (buffer - // was drained via sweep/flush before a terminal landed). Same - // sub-agent + protocol-terminal composition as in `ingest_at`. - let terminal: Option<&AgentCall> = calls - .iter() - .rev() - .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal) - .copied(); - - // `terminal` is `Some` iff a real wire-level terminal landed before - // finalize. Wire-level vocabulary (`end_turn`, `max_tokens`, `refusal`, - // `completed`, …) lives entirely in `final_finish_reason` below; status - // is the lifecycle signal. `status_override` lets the in-progress - // snapshot path pin `InProgress` even when the terminal has already - // landed in the partition (which can happen briefly during the grace - // window — the row should flip to Complete only via the Completed - // event, never via an in-progress snapshot). - let status = status_override.unwrap_or_else(|| match terminal { - Some(_) => TraceStatus::Complete, - None => TraceStatus::Incomplete, - }); - - let (final_answer_preview, final_call_id, final_finish_reason) = match terminal { - Some(ic) => { - let preview = ic - .agent - .assistant_text - .as_deref() - .map(|t| truncate_preview(t, FINAL_ANSWER_PREVIEW_CHARS)); - ( - preview, - Some(ic.call.id.clone()), - ic.call.finish_reason.clone(), - ) - } - None => (None, None, None), - }; - - // Agent-classification rollup across all calls in the partition. - // Topology precedence: Orchestrator > SubAgent > SingleAgent. - let mut surfaces: BTreeSet = BTreeSet::new(); - let mut tool_call_total: u32 = 0; - let mut topology_rank: u8 = 0; - let mut topology: Option = None; - let mut suspicious: Vec = Vec::new(); - for ic in calls { - if let Some(s) = ic.agent.tool_surface { - surfaces.insert(s); - } - tool_call_total = tool_call_total.saturating_add(ic.agent.tool_call_count); - - if let Some(t) = ic.agent.agent_topology { - let rank = match t { - AgentTopology::Orchestrator => 2, - AgentTopology::SubAgent => 1, - AgentTopology::SingleAgent => 0, - }; - if rank >= topology_rank { - topology_rank = rank; - topology = Some(t); - } - } - - for sig in &ic.agent.suspicious_signals { - match sig { - SuspiciousSignal::UnknownToolName { name } => { - suspicious.push(SuspiciousSkillRollup { - tool_name: name.clone(), - reason: "unknown_tool_name".to_string(), - }); - } - } - } - } - // Deduplicate suspicious by tool_name (keep first occurrence). - let mut seen: BTreeSet = BTreeSet::new(); - suspicious.retain(|s| seen.insert(s.tool_name.clone())); - let tool_surfaces: Vec = surfaces.into_iter().collect(); - - Trace { - source_id, - turn_id, - session_id, - wire_api, - agent_kind, - client_ip, - server_ip, - start_time_us, - end_time_us, - duration_ms, - call_count, - models_used, - subagents_used, - total_input_tokens, - total_output_tokens, - total_cache_read_input_tokens, - total_cache_creation_input_tokens, - total_cost_usd: None, - status, - final_finish_reason, - user_input_preview, - user_call_id, - final_answer_preview, - final_call_id, - span_ids, - metadata: serde_json::json!({}), - tool_surfaces, - tool_call_total, - agent_topology: topology, - suspicious_skills: suspicious, - } -} +#[cfg(test)] +include!("tracker_reference.rs"); #[cfg(test)] mod tests { use super::*; - use std::net::IpAddr; - use std::sync::Arc; use h_common::internal_metrics::MetricsSystem; use h_llm::agents; use h_llm::model::{AgentCall, AgentCallInfo, ApiType, LlmCall}; use h_llm::wire_apis as wa; + use std::net::IpAddr; + use std::sync::Arc; fn test_metrics() -> MetricsWorker { let mut sys = MetricsSystem::new(); @@ -1190,6 +1059,212 @@ mod tests { .collect() } + #[test] + fn ingest_releases_full_calls_and_preserves_turn_summary() { + // Keeping the incoming Arc in pending must fail this ownership contract: + // storage alone owns raw bodies/headers after the tracker ingests a call. + let registry = crate::model::new_active_trace_registry(); + let mut tracker = + TurnTracker::with_registry(TrackerConfig::default(), test_metrics(), Some(registry)); + let now = Instant::now(); + for index in 0..2 { + let mut identified = crate::test_support::make_call( + if index == 0 { "opening" } else { "terminal" }, + Some(if index == 0 { + ToolSurface::Cli + } else { + ToolSurface::Mcp + }), + 2 + index, + &["odd-tool"], + ); + let call = Arc::get_mut(&mut identified.call).unwrap(); + call.source_id = "compact-source".into(); + call.request_time = 1_000_000 + i64::from(index) * 1_000_000; + call.response_time = Some(call.request_time + 100_000); + call.complete_time = Some(call.request_time + 200_000); + call.model = if index == 0 { + "first-model" + } else { + "last-model" + } + .into(); + call.finish_reason = Some(if index == 0 { "tool_use" } else { "end_turn" }.into()); + call.input_tokens = Some(11 + index); + call.output_tokens = Some(3 + index); + call.cache_read_input_tokens = Some(5 + index); + call.cache_creation_input_tokens = Some(7 + index); + call.request_body = Some("q".repeat(1024 * 1024)); + call.response_body = Some("r".repeat(1024 * 1024)); + call.request_headers = vec![("x-large-request".into(), "h".repeat(64 * 1024))]; + call.response_headers = vec![("x-large-response".into(), "j".repeat(64 * 1024))]; + call.process = Some(h_common::process::ProcessInfo::new(42, "test-agent")); + identified.agent.session_id = "compact-session".into(); + identified.agent.is_user_turn_start = Some(index == 0); + identified.agent.is_turn_terminal = index == 1; + identified.agent.user_input = Some(if index == 0 { "界" } else { "续" }.repeat(4096)); + identified.agent.assistant_text = + Some(if index == 0 { "中" } else { "终" }.repeat(4096)); + identified.agent.agent_topology = Some(if index == 0 { + AgentTopology::SingleAgent + } else { + AgentTopology::Orchestrator + }); + identified.agent.suspicious_signals = vec![SuspiciousSignal::UnknownToolName { + name: "odd-tool".into(), + }]; + + let storage_call = identified.call.clone(); + let full_call = Arc::downgrade(&storage_call); + assert!(tracker + .ingest_at(identified, now + Duration::from_millis(u64::from(index))) + .is_empty()); + assert_eq!( + storage_call.request_body.as_ref().unwrap().len(), + 1024 * 1024 + ); + assert!(storage_call + .request_body + .as_ref() + .unwrap() + .bytes() + .all(|b| b == b'q')); + assert_eq!( + storage_call.response_body.as_ref().unwrap().len(), + 1024 * 1024 + ); + assert!(storage_call + .response_body + .as_ref() + .unwrap() + .bytes() + .all(|b| b == b'r')); + assert_eq!(storage_call.request_headers[0].1, "h".repeat(64 * 1024)); + assert_eq!(storage_call.response_headers[0].1, "j".repeat(64 * 1024)); + assert_eq!(storage_call.process.as_ref().unwrap().pid, 42); + drop(storage_call); + assert!( + full_call.upgrade().is_none(), + "turn pending must not retain the full call after storage releases it" + ); + } + + // Text retained for turn previews must be bounded too; full text remains + // on the independently owned storage call, never in this metadata buffer. + for buffered in tracker.buffers.values().flat_map(|b| b.pending.values()) { + assert!( + buffered + .ic + .agent + .user_input + .as_ref() + .unwrap() + .chars() + .count() + <= 501 + ); + assert!( + buffered + .ic + .agent + .assistant_text + .as_ref() + .unwrap() + .chars() + .count() + <= 501 + ); + } + let active = tracker.snapshot_active(); + assert_eq!(active.len(), 1); + assert_eq!(active[0].status, TraceStatus::InProgress); + assert_eq!(active[0].span_ids, ["opening", "terminal"]); + let active_id = active[0].turn_id.clone(); + let turns = drain_completed(tracker.advance_time_at( + 2_200_000, + "compact-source", + now + Duration::from_secs(2), + )); + assert_eq!(turns.len(), 1); + let turn = &turns[0]; + assert_eq!(turn.turn_id, active_id); + assert_eq!(turn.status, TraceStatus::Complete); + assert_eq!(turn.source_id, "compact-source"); + assert_eq!(turn.session_id, "compact-session"); + assert_eq!(turn.wire_api, "anthropic"); + assert_eq!(turn.agent_kind, "test"); + assert_eq!(turn.client_ip, "127.0.0.1".parse::().unwrap()); + assert_eq!(turn.server_ip, "127.0.0.1".parse::().unwrap()); + assert_eq!(turn.start_time_us, 1_000_000); + assert_eq!(turn.end_time_us, 2_200_000); + assert_eq!(turn.duration_ms, 1200); + assert_eq!(turn.call_count, 2); + assert_eq!(turn.span_ids, ["opening", "terminal"]); + assert_eq!(turn.models_used, ["first-model", "last-model"]); + assert!(turn.subagents_used.is_empty()); + assert_eq!(turn.total_input_tokens, 23); + assert_eq!(turn.total_output_tokens, 7); + assert_eq!(turn.total_cache_read_input_tokens, 11); + assert_eq!(turn.total_cache_creation_input_tokens, 15); + assert_eq!(turn.final_finish_reason.as_deref(), Some("end_turn")); + assert_eq!(turn.user_call_id.as_deref(), Some("opening")); + assert_eq!(turn.final_call_id.as_deref(), Some("terminal")); + assert_eq!( + turn.user_input_preview, + Some(format!("{}…", "界".repeat(500))) + ); + assert_eq!( + turn.final_answer_preview, + Some(format!("{}…", "终".repeat(500))) + ); + assert_eq!(turn.tool_surfaces, [ToolSurface::Mcp, ToolSurface::Cli]); + assert_eq!(turn.tool_call_total, 5); + assert_eq!(turn.agent_topology, Some(AgentTopology::Orchestrator)); + assert_eq!(turn.suspicious_skills.len(), 1); + assert_eq!(turn.suspicious_skills[0].tool_name, "odd-tool"); + assert_eq!(turn.suspicious_skills[0].reason, "unknown_tool_name"); + assert!(tracker.snapshot_active().is_empty()); + assert_eq!(tracker.active_count(), 0); + } + + // @scenario TURN-COMPACT-001 unit + #[test] + fn compact_pending_preserves_pid_fallback_without_full_call_ownership() { + let mut tracker = mk_tracker_no_grace(); + let mut identified = crate::test_support::make_call("pid-call", None, 0, &[]); + Arc::get_mut(&mut identified.call).unwrap().process = + Some(h_common::process::ProcessInfo::new(73, "test-agent")); + identified.agent.session_id = "pid-session".into(); + identified.agent.user_input = Some("observed continuation".into()); + let storage_call = identified.call.clone(); + let full_call = Arc::downgrade(&storage_call); + assert!(tracker.ingest(identified).is_empty()); + drop(storage_call); + assert!( + full_call.upgrade().is_none(), + "PID evidence must not retain the raw call" + ); + let turns = drain_completed(tracker.flush_all()); + assert_eq!( + turns.len(), + 1, + "PID fallback must still keep a missed-opening turn" + ); + assert_eq!(turns[0].status, TraceStatus::Incomplete); + assert_eq!(turns[0].span_ids, ["pid-call"]); + assert_eq!( + turns[0].user_input_preview.as_deref(), + Some("observed continuation") + ); + assert_eq!( + tracker + .metrics + .counter(Metric::TurnKeptByPidAttribution) + .get(), + 1 + ); + } + #[test] fn tracker_starts_empty() { let t = TurnTracker::new(TrackerConfig::default(), test_metrics()); @@ -1387,8 +1462,7 @@ mod tests { #[test] fn pid_attribution_keeps_turn_when_opening_call_missed() { let metrics = test_metrics(); - let mut t = - TurnTracker::new(TrackerConfig::default(), metrics.clone()); + let mut t = TurnTracker::new(TrackerConfig::default(), metrics.clone()); // Two continuation calls (tool_result bodies → is_user_turn_start=false), // both carrying the same eBPF PID. The second closes the turn (end_turn). @@ -1427,8 +1501,7 @@ mod tests { // fire — a partition with no user-start and no process attribution // is still discarded, exactly as before. let metrics = test_metrics(); - let mut t = - TurnTracker::new(TrackerConfig::default(), metrics.clone()); + let mut t = TurnTracker::new(TrackerConfig::default(), metrics.clone()); let c1 = anthropic_continuation_call("S", 1_000_000, "tool_use", false); let c2 = anthropic_continuation_call("S", 2_000_000, "end_turn", false); @@ -1446,10 +1519,7 @@ mod tests { 0, "fallback must not fire without PID" ); - assert_eq!( - metrics.counter(Metric::TurnDiscardedNoUserStart).get(), - 1, - ); + assert_eq!(metrics.counter(Metric::TurnDiscardedNoUserStart).get(), 1,); } #[test] @@ -1603,7 +1673,7 @@ mod tests { let mut t = mk_tracker_no_grace(); let mut c = codex_call("s1", "t1", "message", "completed"); c.response_body = Some( - r#"{"output":[ + r#"{"status":"completed","output":[ {"type":"reasoning","summary":[]}, {"type":"message","role":"assistant","content":[{"type":"output_text","text":"done."}]} ]}"# @@ -1696,7 +1766,7 @@ mod tests { c2.request_time = 2_000_000; c2.complete_time = Some(2_500_000); c2.response_body = Some( - r#"{"output":[ + r#"{"status":"completed","output":[ {"type":"message","role":"assistant","content":[{"type":"output_text","text":"done."}]} ]}"# .to_string(), @@ -1743,6 +1813,8 @@ mod tests { (t, reg) } + include!("tracker_longrun_tests.rs"); + fn registry_snapshot(reg: &crate::model::ActiveTraceRegistry) -> Vec { reg.read().unwrap().values().cloned().collect() } diff --git a/server/h-turn/src/tracker_aggregate.rs b/server/h-turn/src/tracker_aggregate.rs new file mode 100644 index 00000000..f98eb7cd --- /dev/null +++ b/server/h-turn/src/tracker_aggregate.rs @@ -0,0 +1,169 @@ +//! Incremental Trace rollup shared by active snapshots and final assembly. + +use std::collections::HashSet; + +use super::{main_agent_user_turn_start, TurnCall}; +use crate::model::{Trace, TraceStatus}; +use crate::SuspiciousSkillRollup; +use h_common::agent::AgentTopology; +use h_llm::agent_classifier::SuspiciousSignal; +use uuid::Uuid; + +#[derive(Debug, Default)] +pub(super) struct TraceRollup { + models: HashSet, + subagents: HashSet, + suspicious: HashSet, + has_user_start: bool, + has_pid: bool, + has_fallback: bool, +} + +impl TraceRollup { + pub(super) fn observe_eligibility(&mut self, ic: &TurnCall) { + self.has_user_start |= main_agent_user_turn_start(ic); + self.has_pid |= ic.agent.subagent_name.is_none() && ic.call.has_process; + } + + pub(super) fn eligible(&self) -> bool { + self.has_user_start || self.has_pid + } + + pub(super) fn append(&mut self, turn: &mut Trace, ic: &TurnCall) { + turn.span_ids.push(ic.call.id.clone()); + turn.call_count += 1; + turn.end_time_us = turn.end_time_us.max( + ic.call + .complete_time + .or(ic.call.response_time) + .unwrap_or(ic.call.request_time), + ); + turn.duration_ms = ((turn.end_time_us - turn.start_time_us).max(0) / 1000) as u64; + if self.models.insert(ic.call.model.clone()) { + turn.models_used.push(ic.call.model.clone()); + } + if let Some(name) = &ic.agent.subagent_name { + if self.subagents.insert(name.clone()) { + turn.subagents_used.push(name.clone()); + } + } + turn.total_input_tokens += u64::from(ic.call.input_tokens.unwrap_or(0)); + turn.total_output_tokens += u64::from(ic.call.output_tokens.unwrap_or(0)); + turn.total_cache_read_input_tokens += + u64::from(ic.call.cache_read_input_tokens.unwrap_or(0)); + turn.total_cache_creation_input_tokens += + u64::from(ic.call.cache_creation_input_tokens.unwrap_or(0)); + // A real first user-start supersedes the PID fallback even when its + // text is absent: clear both preview and user_call_id in that case. + let user_start = main_agent_user_turn_start(ic); + let fallback = ic.agent.subagent_name.is_none() && ic.agent.user_input.is_some(); + if !self.has_user_start && (user_start || (!self.has_fallback && fallback)) { + turn.user_input_preview = ic.agent.user_input.clone(); + turn.user_call_id = ic.agent.user_input.as_ref().map(|_| ic.call.id.clone()); + self.has_fallback |= fallback; + } + self.observe_eligibility(ic); + if ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal { + turn.final_answer_preview = ic.agent.assistant_text.clone(); + turn.final_call_id = Some(ic.call.id.clone()); + turn.final_finish_reason = ic.call.finish_reason.clone(); + turn.status = TraceStatus::Complete; + } + // Tool surfaces retain their established enum order. Other unique + // collections retain first occurrence order via the membership sets. + if let Some(surface) = ic.agent.tool_surface { + if let Err(index) = turn.tool_surfaces.binary_search(&surface) { + turn.tool_surfaces.insert(index, surface); + } + } + turn.tool_call_total = turn + .tool_call_total + .saturating_add(ic.agent.tool_call_count); + if let Some(topology) = ic.agent.agent_topology { + fn rank(topology: AgentTopology) -> u8 { + match topology { + AgentTopology::Orchestrator => 2, + AgentTopology::SubAgent => 1, + AgentTopology::SingleAgent => 0, + } + } + if turn + .agent_topology + .is_none_or(|old| rank(topology) >= rank(old)) + { + turn.agent_topology = Some(topology); + } + } + for signal in &ic.agent.suspicious_signals { + match signal { + SuspiciousSignal::UnknownToolName { name } + if self.suspicious.insert(name.clone()) => + { + turn.suspicious_skills.push(SuspiciousSkillRollup { + tool_name: name.clone(), + reason: "unknown_tool_name".into(), + }); + } + _ => {} + } + } + } +} + +pub(super) fn build_turn_with_rollup( + calls: &[&TurnCall], + turn_id_override: Option, + status_override: Option, +) -> (Trace, TraceRollup) { + let first = calls + .first() + .expect("build_turn requires at least one call"); + let mut turn = Trace { + source_id: first.call.source_id.clone(), + turn_id: turn_id_override.unwrap_or_else(|| Uuid::now_v7().to_string()), + session_id: first.agent.session_id.clone(), + wire_api: first.call.wire_api.to_string(), + agent_kind: first.agent.agent_kind.to_string(), + client_ip: first.call.client_ip, + server_ip: first.call.server_ip, + start_time_us: first.call.request_time, + end_time_us: i64::MIN, + duration_ms: 0, + call_count: 0, + models_used: Vec::new(), + subagents_used: Vec::new(), + total_input_tokens: 0, + total_output_tokens: 0, + total_cache_read_input_tokens: 0, + total_cache_creation_input_tokens: 0, + total_cost_usd: None, + status: TraceStatus::Incomplete, + final_finish_reason: None, + user_input_preview: None, + user_call_id: None, + final_answer_preview: None, + final_call_id: None, + span_ids: Vec::with_capacity(calls.len()), + metadata: serde_json::json!({}), + tool_surfaces: Vec::new(), + tool_call_total: 0, + agent_topology: None, + suspicious_skills: Vec::new(), + }; + let mut rollup = TraceRollup::default(); + for call in calls { + rollup.append(&mut turn, call); + } + if let Some(status) = status_override { + turn.status = status; + } + (turn, rollup) +} + +pub(super) fn build_turn( + calls: &[&TurnCall], + turn_id_override: Option, + status_override: Option, +) -> Trace { + build_turn_with_rollup(calls, turn_id_override, status_override).0 +} diff --git a/server/h-turn/src/tracker_longrun_tests.rs b/server/h-turn/src/tracker_longrun_tests.rs new file mode 100644 index 00000000..7629758f --- /dev/null +++ b/server/h-turn/src/tracker_longrun_tests.rs @@ -0,0 +1,577 @@ +// Fail-first regressions for partition ownership and bounded sequential work. +fn longrun_call(id: &str, session: &str, ts: i64, user_start: bool, terminal: bool) -> AgentCall { + let mut ic = crate::test_support::make_call(id, None, 0, &[]); + let call = Arc::get_mut(&mut ic.call).unwrap(); + call.source_id = "synthetic-source".into(); + call.request_time = ts; + call.response_time = Some(ts + 10); + call.complete_time = Some(ts + 20); + call.finish_reason = Some(if terminal { "end_turn" } else { "tool_use" }.into()); + ic.agent.session_id = session.into(); + ic.agent.is_user_turn_start = Some(user_start); + ic.agent.is_turn_terminal = terminal; + ic.agent.user_input = user_start.then(|| format!("input-{id}")); + ic.agent.assistant_text = terminal.then(|| format!("answer-{id}")); + ic +} + +// @scenario TURN-ACTIVE-LIFECYCLE-001 unit +#[test] +fn longrun_out_of_order_discard_drains_64_groups_without_ghosts() { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + let mut original_ids = HashMap::new(); + for group in 0..64 { + let session = format!("group-{group}"); + tracker.ingest_at( + longrun_call(&format!("valid-{group}"), &session, 200, true, false), + now, + ); + original_ids.insert( + session, + registry_snapshot(®istry) + .into_iter() + .find(|t| t.session_id == format!("group-{group}")) + .unwrap() + .turn_id, + ); + tracker.ingest_at( + longrun_call( + &format!("orphan-{group}"), + &format!("group-{group}"), + 100, + false, + true, + ), + now, + ); + } + assert_eq!(tracker.active_count(), 128); + let turns = drain_completed(tracker.flush_all_at(now)); + assert_eq!(turns.len(), 64); + assert!(turns + .iter() + .all(|t| t.status == TraceStatus::Incomplete && t.call_count == 1)); + assert!( + registry_snapshot(®istry).is_empty(), + "drain must leave zero ghost InProgress rows" + ); + for turn in turns { + assert_eq!( + turn.turn_id, original_ids[&turn.session_id], + "older discard must not steal the valid partition's snapshot ID" + ); + } + assert_eq!(tracker.active_count(), 0); +} + +// @scenario TURN-ACTIVE-LIFECYCLE-001 unit +#[test] +fn longrun_late_eligibility_preserves_tail_id_after_heartbeat_discard() { + for eligible_by_pid in [false, true] { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + tracker.ingest_at(longrun_call("prefix", "session", 100, false, false), now); + assert!(registry_snapshot(®istry).is_empty()); + let mut valid = longrun_call("valid", "session", 200, !eligible_by_pid, false); + if eligible_by_pid { + Arc::get_mut(&mut valid.call).unwrap().process = + Some(h_common::process::ProcessInfo::new(7, "test-agent")); + } + tracker.ingest_at(valid, now); + let initial = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(initial.span_ids, ["prefix", "valid"]); + tracker.ingest_at(longrun_call("orphan", "session", 150, false, true), now); + assert!(registry_snapshot(®istry).is_empty()); + + let after_grace = now + Duration::from_secs(2); + assert!(tracker + .advance_time_at(220, "synthetic-source", after_grace) + .is_empty()); + let tail = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(tail.span_ids, ["valid"]); + assert_eq!( + tail.turn_id, initial.turn_id, + "discarded ineligible prefix must not consume the valid tail's ID" + ); + assert_eq!( + tracker + .metrics + .counter(Metric::TurnDiscardedNoUserStart) + .get(), + 1 + ); + let final_turns = drain_completed(tracker.flush_all_at(after_grace)); + assert_eq!(final_turns.len(), 1); + assert_eq!(final_turns[0].span_ids, ["valid"]); + assert_eq!(final_turns[0].status, TraceStatus::Incomplete); + assert_eq!(final_turns[0].turn_id, initial.turn_id); + assert_eq!(tracker.active_count(), 0); + assert!(registry_snapshot(®istry).is_empty()); + } +} + +// @scenario TURN-ACTIVE-LIFECYCLE-001 unit +#[test] +fn longrun_late_eligibility_preserves_tail_id_after_eof_discard() { + for eligible_by_pid in [false, true] { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + tracker.ingest_at(longrun_call("prefix", "session", 100, false, false), now); + let mut valid = longrun_call("valid", "session", 200, !eligible_by_pid, false); + if eligible_by_pid { + Arc::get_mut(&mut valid.call).unwrap().process = + Some(h_common::process::ProcessInfo::new(7, "test-agent")); + } + tracker.ingest_at(valid, now); + let initial = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(initial.span_ids, ["prefix", "valid"]); + tracker.ingest_at(longrun_call("orphan", "session", 150, false, true), now); + let final_turns = drain_completed(tracker.flush_all_at(now)); + assert_eq!(final_turns.len(), 1); + assert_eq!(final_turns[0].span_ids, ["valid"]); + assert_eq!(final_turns[0].status, TraceStatus::Incomplete); + assert_eq!( + final_turns[0].turn_id, initial.turn_id, + "EOF discard must preserve the surviving eligible call's ID" + ); + assert_eq!( + tracker + .metrics + .counter(Metric::TurnDiscardedNoUserStart) + .get(), + 1 + ); + assert_eq!(tracker.active_count(), 0); + assert!(registry_snapshot(®istry).is_empty()); + } +} + +#[test] +fn longrun_eligible_prefix_retains_id_when_terminal_splits_valid_tail() { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + tracker.ingest_at(longrun_call("prefix", "session", 100, true, false), now); + tracker.ingest_at(longrun_call("tail", "session", 200, true, false), now); + let initial = registry_snapshot(®istry).pop().unwrap(); + tracker.ingest_at(longrun_call("terminal", "session", 150, false, true), now); + let completed = drain_completed(tracker.advance_time_at( + 220, + "synthetic-source", + now + Duration::from_secs(2), + )); + assert_eq!(completed.len(), 1); + assert_eq!(completed[0].span_ids, ["prefix", "terminal"]); + assert_eq!(completed[0].status, TraceStatus::Complete); + assert_eq!(completed[0].turn_id, initial.turn_id); + let tail = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(tail.span_ids, ["tail"]); + assert_ne!( + tail.turn_id, initial.turn_id, + "eligible earlier partition keeps its own ID" + ); + let drained = drain_completed(tracker.flush_all_at(now)); + assert_eq!(drained.len(), 1); + assert_eq!(drained[0].turn_id, tail.turn_id); + assert!(registry_snapshot(®istry).is_empty()); +} + +#[test] +fn longrun_earlier_terminal_hides_displaced_snapshot_until_tail_is_ready() { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + tracker.ingest_at(longrun_call("valid", "session", 200, true, false), now); + let tail_id = registry_snapshot(®istry)[0].turn_id.clone(); + tracker.ingest_at(longrun_call("orphan", "session", 100, false, true), now); + assert!( + registry_snapshot(®istry).is_empty(), + "snapshot must represent the current eligible head only" + ); + assert!(tracker + .advance_time_at(220, "synthetic-source", now + Duration::from_secs(2)) + .is_empty()); + let snapshots = registry_snapshot(®istry); + assert_eq!(snapshots.len(), 1); + assert_eq!(snapshots[0].turn_id, tail_id); + assert_eq!(snapshots[0].span_ids, ["valid"]); +} + +#[test] +fn longrun_heartbeat_finalization_publishes_tail_without_more_ingest() { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + for call in [ + longrun_call("opening", "session", 100, true, false), + longrun_call("terminal", "session", 200, false, true), + longrun_call("tail", "session", 300, true, false), + ] { + tracker.ingest_at(call, now); + } + let head = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(head.span_ids, ["opening", "terminal"]); + let turns = drain_completed(tracker.advance_time_at( + 320, + "synthetic-source", + now + Duration::from_secs(2), + )); + assert_eq!(turns.len(), 1); + assert_eq!(turns[0].turn_id, head.turn_id); + let tail = registry_snapshot(®istry) + .pop() + .expect("heartbeat must publish valid tail immediately"); + assert_eq!(tail.span_ids, ["tail"]); + assert_ne!(tail.turn_id, head.turn_id); + let drained = drain_completed(tracker.flush_all_at(now + Duration::from_secs(2))); + assert_eq!(drained[0].turn_id, tail.turn_id); + assert!(registry_snapshot(®istry).is_empty()); +} + +// @scenario TURN-ACTIVE-LIFECYCLE-001 unit +#[test] +fn longrun_other_source_grace_expiry_sweeps_newly_idle_tail() { + let config = TrackerConfig { + idle_timeout_us: 100, + sweep_interval_us: 1, + ..TrackerConfig::default() + }; + let registry = crate::new_active_trace_registry(); + let mut tracker = TurnTracker::with_registry(config, test_metrics(), Some(registry.clone())); + let now = Instant::now(); + for call in [ + longrun_call("opening", "session", 100, true, false), + longrun_call("terminal", "session", 200, false, true), + longrun_call("tail", "session", 300, true, false), + ] { + tracker.ingest_at(call, now); + } + // This source has already advanced far enough for idle, but grace still + // protects the head. The next sweep is driven by a different source. + assert!(tracker + .advance_time_at(1000, "synthetic-source", now) + .is_empty()); + let turns = drain_completed(tracker.advance_time_at( + 1001, + "other-source", + now + Duration::from_secs(2), + )); + assert_eq!( + turns.len(), + 2, + "newly idle tail must be considered in this sweep" + ); + assert_eq!(turns[0].status, TraceStatus::Complete); + assert_eq!(turns[1].status, TraceStatus::Incomplete); + assert_eq!(turns[1].span_ids, ["tail"]); + assert_eq!(tracker.active_count(), 0); + assert!(registry_snapshot(®istry).is_empty()); +} + +#[test] +fn longrun_idle_after_discard_retires_only_the_represented_partition() { + let cfg = TrackerConfig { + idle_timeout_us: 100, + sweep_interval_us: 1, + ..TrackerConfig::default() + }; + let registry = crate::new_active_trace_registry(); + let mut tracker = TurnTracker::with_registry(cfg, test_metrics(), Some(registry.clone())); + let now = Instant::now(); + tracker.ingest_at(longrun_call("valid", "session", 200, true, false), now); + let id = registry_snapshot(®istry)[0].turn_id.clone(); + tracker.ingest_at(longrun_call("orphan", "session", 100, false, true), now); + let turns = drain_completed(tracker.advance_time_at( + 1000, + "synthetic-source", + now + Duration::from_secs(2), + )); + assert_eq!(turns.len(), 1); + assert_eq!(turns[0].turn_id, id); + assert_eq!(turns[0].status, TraceStatus::Incomplete); + assert!(registry_snapshot(®istry).is_empty()); +} + +#[test] +fn longrun_drop_removes_only_own_snapshots_from_shared_registry() { + let registry = crate::new_active_trace_registry(); + let mut first = TurnTracker::with_registry( + TrackerConfig::default(), + test_metrics(), + Some(registry.clone()), + ); + let mut second = TurnTracker::with_registry( + TrackerConfig::default(), + test_metrics(), + Some(registry.clone()), + ); + let now = Instant::now(); + first.ingest_at( + longrun_call("first", "first-session", 100, true, false), + now, + ); + second.ingest_at( + longrun_call("second", "second-session", 100, true, false), + now, + ); + assert_eq!(registry_snapshot(®istry).len(), 2); + drop(first); + let snapshots = registry_snapshot(®istry); + assert_eq!(snapshots.len(), 1, "tracker exit must remove its snapshots"); + assert_eq!(snapshots[0].span_ids, ["second"]); + second.flush_all_at(now); + assert!(registry_snapshot(®istry).is_empty()); +} + +fn assert_trace_fields(actual: &Trace, expected: &Trace) { + macro_rules! fields { ($($field:ident),+ $(,)?) => { $(assert_eq!(actual.$field, expected.$field, "Trace.{}", stringify!($field));)+ }; } + fields!( + source_id, + turn_id, + session_id, + wire_api, + agent_kind, + client_ip, + server_ip, + start_time_us, + end_time_us, + duration_ms, + call_count, + models_used, + subagents_used, + total_input_tokens, + total_output_tokens, + total_cache_read_input_tokens, + total_cache_creation_input_tokens, + total_cost_usd, + status, + final_finish_reason, + user_input_preview, + user_call_id, + final_answer_preview, + final_call_id, + span_ids, + metadata, + tool_surfaces, + tool_call_total, + agent_topology, + suspicious_skills + ); +} + +// @scenario TURN-INCREMENTAL-001 unit +#[test] +fn longrun_snapshots_and_final_fields_match_reference_for_boundary_cases() { + let now = Instant::now(); + let mut pid = longrun_call("pid", "reference", 100, false, false); + Arc::get_mut(&mut pid.call).unwrap().process = + Some(h_common::process::ProcessInfo::new(7, "test-agent")); + pid.agent.user_input = Some("fallback".into()); + let mut user_without_text = longrun_call("user", "reference", 200, true, false); + user_without_text.agent.user_input = None; + let mut subagent = longrun_call("subagent", "reference", 200, true, true); + subagent.agent.subagent_name = Some("worker".into()); + subagent.agent.tool_call_count = 9; + subagent.agent.tool_surface = Some(ToolSurface::Mcp); + subagent.agent.agent_topology = Some(AgentTopology::SubAgent); + subagent.agent.suspicious_signals = + vec![SuspiciousSignal::UnknownToolName { name: "odd".into() }]; + let mut terminal = longrun_call("terminal", "reference", 300, false, true); + terminal.agent.tool_call_count = u32::MAX; + terminal.agent.tool_surface = Some(ToolSurface::Cli); + terminal.agent.agent_topology = Some(AgentTopology::Orchestrator); + terminal.agent.suspicious_signals = subagent.agent.suspicious_signals.clone(); + let mut late_end = longrun_call("late-end", "reference", 50, false, true); + late_end.agent.tool_call_count = 1; + let mut slow = longrun_call("slow", "reference", 100, true, false); + Arc::get_mut(&mut slow.call).unwrap().complete_time = Some(1_000_000); + let sequences = vec![ + vec![ + pid.clone(), + user_without_text.clone(), + subagent.clone(), + terminal.clone(), + ], + vec![ + slow.clone(), + subagent.clone(), + terminal.clone(), + longrun_call("tail", "reference", 300, true, false), + ], + vec![terminal.clone(), subagent.clone(), slow.clone()], + vec![slow.clone(), late_end, terminal.clone()], + vec![ + slow, + terminal, + longrun_call("tail", "reference", 400, true, false), + ], + ]; + for sequence in sequences { + let (mut tracker, registry) = mk_tracker_with_registry(); + let mut arrived: Vec = Vec::new(); + for call in sequence { + arrived.push(call.clone().into()); + tracker.ingest_at(call, now); + let mut sorted: Vec<&TurnCall> = arrived.iter().collect(); + sorted.sort_by_key(|ic| ic.call.request_time); + let head_len = sorted + .iter() + .position(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal) + .map_or(sorted.len(), |i| i + 1); + let head = &sorted[..head_len]; + let eligible = head.iter().any(|ic| main_agent_user_turn_start(ic)) + || partition_has_pid_attribution(head.iter().copied()); + let snapshots = registry_snapshot(®istry); + if eligible { + assert_eq!(snapshots.len(), 1); + let expected = build_turn_reference( + head, + Some(snapshots[0].turn_id.clone()), + Some(TraceStatus::InProgress), + ); + assert_trace_fields(&snapshots[0], &expected); + } else { + assert!(snapshots.is_empty()); + } + } + let final_turns = drain_completed(tracker.flush_all_at(now)); + let mut sorted: Vec<&TurnCall> = arrived.iter().collect(); + sorted.sort_by_key(|ic| ic.call.request_time); + let mut expected_parts = Vec::new(); + while !sorted.is_empty() { + let boundary = sorted + .iter() + .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal) + .map(|ic| ic.call.request_time); + let n = boundary.map_or(sorted.len(), |ts| { + sorted + .iter() + .take_while(|ic| ic.call.request_time <= ts) + .count() + }); + let part: Vec<_> = sorted.drain(..n).collect(); + if part.iter().any(|ic| main_agent_user_turn_start(ic)) + || partition_has_pid_attribution(part.iter().copied()) + { + expected_parts.push(part); + } + } + assert_eq!(final_turns.len(), expected_parts.len()); + for (actual, calls) in final_turns.iter().zip(expected_parts) { + let expected = build_turn_reference(&calls, Some(actual.turn_id.clone()), None); + assert_trace_fields(actual, &expected); + } + assert!(registry_snapshot(®istry).is_empty()); + } +} + +// @scenario TURN-INCREMENTAL-001 unit +#[test] +fn longrun_ordered_1000_2000_4000_calls_have_linear_snapshot_work() { + let mut measured = Vec::new(); + for n in [1000, 2000, 4000] { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + reset_work(); + let started = Instant::now(); + for i in 0..n { + let mut call = longrun_call( + &format!("call-{i}"), + "ordered", + 1000 + i as i64, + i == 0, + false, + ); + Arc::get_mut(&mut call.call).unwrap().model = format!("model-{}", i % 7); + call.agent.suspicious_signals = vec![SuspiciousSignal::UnknownToolName { + name: format!("tool-{}", i % 11), + }]; + tracker.ingest_at(call, now); + assert_eq!(tracker.active_count(), i + 1); + assert!(tracker.sweep().is_empty()); + } + let elapsed = started.elapsed(); + let before_drain = work(); + let snapshot = registry_snapshot(®istry).pop().unwrap(); + assert_eq!(snapshot.call_count, n as u32); + assert_eq!(snapshot.models_used.len(), 7); + assert_eq!(snapshot.suspicious_skills.len(), 11); + let final_turns = drain_completed(tracker.flush_all_at(now)); + assert_eq!(final_turns.len(), 1); + assert_eq!(final_turns[0].turn_id, snapshot.turn_id); + let after_drain = work(); + println!( + "ordered n={n} ingest_us={} work={before_drain:?} after_drain={after_drain:?}", + elapsed.as_micros() + ); + measured.push((n, before_drain, after_drain)); + } + for (n, before, after) in measured { + assert!( + before.snapshot_visits <= 2 * n, + "ordered snapshot revisits calls: {before:?}" + ); + assert!( + before.session_visits <= 4 * n, + "ordered ingest scans unrelated buffers: {before:?}" + ); + assert_eq!(after.final_visits, n, "build one final Trace per partition"); + } +} + +#[test] +fn longrun_stacked_terminals_and_ineligible_streams_have_linear_work() { + let mut measured = Vec::new(); + for mode in ["terminals", "ineligible", "sessions"] { + let (mut tracker, registry) = mk_tracker_with_registry(); + let now = Instant::now(); + let n = 4000; + reset_work(); + let started = Instant::now(); + for i in 0..n { + let session = if mode == "sessions" { + format!("session-{i}") + } else { + "one".into() + }; + let call = longrun_call( + &format!("call-{i}"), + &session, + i as i64, + mode != "ineligible", + mode == "terminals", + ); + tracker.ingest_at(call, now); + assert_eq!(tracker.active_count(), i + 1); + assert!(tracker.sweep().is_empty()); + } + let turns = drain_completed(tracker.flush_all_at(now)); + assert_eq!( + turns.len(), + match mode { + "ineligible" => 0, + "terminals" | "sessions" => n, + _ => unreachable!(), + } + ); + assert!(registry_snapshot(®istry).is_empty()); + let counts = work(); + println!( + "{mode} n={n} total_us={} work={counts:?}", + started.elapsed().as_micros() + ); + measured.push((mode, n, counts)); + } + for (mode, n, counts) in measured { + assert!( + counts.snapshot_visits <= 3 * n, + "{mode}: repeated snapshot scans: {counts:?}" + ); + assert!( + counts.terminal_visits <= 3 * n, + "{mode}: repeated terminal scans: {counts:?}" + ); + assert!( + counts.session_visits <= 8 * n, + "{mode}: repeated session scans: {counts:?}" + ); + } +} diff --git a/server/h-turn/src/tracker_reference.rs b/server/h-turn/src/tracker_reference.rs new file mode 100644 index 00000000..e51bc173 --- /dev/null +++ b/server/h-turn/src/tracker_reference.rs @@ -0,0 +1,215 @@ +// Original full-scan builder retained as an independent equivalence oracle. +fn push_unique(list: &mut Vec, value: String) { + if !list.iter().any(|v| v == &value) { + list.push(value); + } +} + +/// Pure constructor over a request_time-sorted partition. +/// +/// `turn_id_override`: caller-supplied id. Used by the in-progress +/// snapshot path so every snapshot for the same in-flight turn shares +/// one id, and the eventual finalized `Trace` carries the same id +/// the registry has been advertising. `None` mints a fresh UUID. +/// +/// `status_override`: forces a status. Used by the in-progress snapshot +/// path to pin `InProgress` even when the partition's terminal call has +/// already landed (which can happen briefly during the grace window — +/// the user shouldn't see the row flip via a snapshot; that transition +/// belongs to the persisted Completed). `None` falls back to derived +/// status (Complete iff a main-agent terminal is in the partition; +/// Incomplete otherwise). +/// +/// Turn status and `final_*` are both derived from the composed main-agent +/// terminal pick — `agent.subagent_name.is_none() && agent.is_turn_terminal`, +/// where the protocol-terminal field is set at h-llm time. Profiles whose +/// wire-level `finish_reason` cannot distinguish "final answer" from "tool +/// roundtrip pending" (e.g. codex-cli over openai-responses, where every +/// successful call reports `response.completed`) override +/// `AgentProfile::is_turn_terminal` to inspect the body explicitly; the +/// canonical decision lives upstream. For partitions drained via idle-sweep +/// / EOF-flush with no terminal in the buffer, `final_*` stay `None` and +/// status falls to `Incomplete`. +fn build_turn_reference( + calls: &[&TurnCall], + turn_id_override: Option, + status_override: Option, +) -> Trace { + assert!(!calls.is_empty(), "build_turn requires at least one call"); + let first = calls[0]; + let source_id = first.call.source_id.clone(); + let session_id = first.agent.session_id.clone(); + let agent_kind = first.agent.agent_kind.to_string(); + let wire_api = first.call.wire_api.to_string(); + let client_ip = first.call.client_ip; + let server_ip = first.call.server_ip; + let turn_id = turn_id_override.unwrap_or_else(|| Uuid::now_v7().to_string()); + + let start_time_us = first.call.request_time; + let end_time_us = calls + .iter() + .map(|ic| { + ic.call + .complete_time + .or(ic.call.response_time) + .unwrap_or(ic.call.request_time) + }) + .max() + .expect("non-empty"); + let duration_ms = ((end_time_us - start_time_us).max(0) / 1000) as u64; + + let call_count = calls.len() as u32; + let span_ids: Vec = calls.iter().map(|ic| ic.call.id.clone()).collect(); + + let mut models_used: Vec = Vec::new(); + let mut subagents_used: Vec = Vec::new(); + let mut total_input_tokens: u64 = 0; + let mut total_output_tokens: u64 = 0; + let mut total_cache_read_input_tokens: u64 = 0; + let mut total_cache_creation_input_tokens: u64 = 0; + for ic in calls { + push_unique(&mut models_used, ic.call.model.clone()); + if let Some(sa) = ic.agent.subagent_name.as_ref() { + push_unique(&mut subagents_used, sa.clone()); + } + if let Some(t) = ic.call.input_tokens { + total_input_tokens += t as u64; + } + if let Some(t) = ic.call.output_tokens { + total_output_tokens += t as u64; + } + if let Some(t) = ic.call.cache_read_input_tokens { + total_cache_read_input_tokens += t as u64; + } + if let Some(t) = ic.call.cache_creation_input_tokens { + total_cache_creation_input_tokens += t as u64; + } + } + + // user_input: prefer the main-agent call flagged as user-turn-start. + // Fall back to any main-agent call whose body yielded user_input upstream. + let user_pick = calls + .iter() + .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_user_turn_start == Some(true)) + .or_else(|| { + calls + .iter() + .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.user_input.is_some()) + }); + let (user_input_preview, user_call_id) = match user_pick { + Some(ic) => match ic.agent.user_input.as_deref() { + Some(text) => (Some(text.to_string()), Some(ic.call.id.clone())), + None => (None, None), + }, + None => (None, None), + }; + + // Terminal pick: the main-agent call that actually closed this turn. + // Drives both `status` and `final_*`. `None` → turn is Incomplete (buffer + // was drained via sweep/flush before a terminal landed). Same + // sub-agent + protocol-terminal composition as in `ingest_at`. + let terminal: Option<&TurnCall> = calls + .iter() + .rev() + .find(|ic| ic.agent.subagent_name.is_none() && ic.agent.is_turn_terminal) + .copied(); + + // `terminal` is `Some` iff a real wire-level terminal landed before + // finalize. Wire-level vocabulary (`end_turn`, `max_tokens`, `refusal`, + // `completed`, …) lives entirely in `final_finish_reason` below; status + // is the lifecycle signal. `status_override` lets the in-progress + // snapshot path pin `InProgress` even when the terminal has already + // landed in the partition (which can happen briefly during the grace + // window — the row should flip to Complete only via the Completed + // event, never via an in-progress snapshot). + let status = status_override.unwrap_or_else(|| match terminal { + Some(_) => TraceStatus::Complete, + None => TraceStatus::Incomplete, + }); + + let (final_answer_preview, final_call_id, final_finish_reason) = match terminal { + Some(ic) => { + let preview = ic.agent.assistant_text.clone(); + ( + preview, + Some(ic.call.id.clone()), + ic.call.finish_reason.clone(), + ) + } + None => (None, None, None), + }; + + // Agent-classification rollup across all calls in the partition. + // Topology precedence: Orchestrator > SubAgent > SingleAgent. + let mut surfaces: BTreeSet = BTreeSet::new(); + let mut tool_call_total: u32 = 0; + let mut topology_rank: u8 = 0; + let mut topology: Option = None; + let mut suspicious: Vec = Vec::new(); + for ic in calls { + if let Some(s) = ic.agent.tool_surface { + surfaces.insert(s); + } + tool_call_total = tool_call_total.saturating_add(ic.agent.tool_call_count); + + if let Some(t) = ic.agent.agent_topology { + let rank = match t { + AgentTopology::Orchestrator => 2, + AgentTopology::SubAgent => 1, + AgentTopology::SingleAgent => 0, + }; + if rank >= topology_rank { + topology_rank = rank; + topology = Some(t); + } + } + + for sig in &ic.agent.suspicious_signals { + match sig { + SuspiciousSignal::UnknownToolName { name } => { + suspicious.push(SuspiciousSkillRollup { + tool_name: name.clone(), + reason: "unknown_tool_name".to_string(), + }); + } + } + } + } + // Deduplicate suspicious by tool_name (keep first occurrence). + let mut seen: BTreeSet = BTreeSet::new(); + suspicious.retain(|s| seen.insert(s.tool_name.clone())); + let tool_surfaces: Vec = surfaces.into_iter().collect(); + + Trace { + source_id, + turn_id, + session_id, + wire_api, + agent_kind, + client_ip, + server_ip, + start_time_us, + end_time_us, + duration_ms, + call_count, + models_used, + subagents_used, + total_input_tokens, + total_output_tokens, + total_cache_read_input_tokens, + total_cache_creation_input_tokens, + total_cost_usd: None, + status, + final_finish_reason, + user_input_preview, + user_call_id, + final_answer_preview, + final_call_id, + span_ids, + metadata: serde_json::json!({}), + tool_surfaces, + tool_call_total, + agent_topology: topology, + suspicious_skills: suspicious, + } +} diff --git a/verification/scenarios.json b/verification/scenarios.json index b305be07..aaefae96 100644 --- a/verification/scenarios.json +++ b/verification/scenarios.json @@ -65,6 +65,87 @@ "integration" ] }, + { + "id": "CLICKHOUSE-LIST-SUMMARY-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Call lists use exact persisted token-estimation summaries and preserve compatible legacy results.", + "invariant": "Summarized pages never request response bodies; unknown values retain the shared Rust usage rules and complete detail bodies. Legacy NULLs are filled in paced, bounded, resumable batches.", + "verification": [ + "unit", + "integration" + ] + }, + { + "id": "CLICKHOUSE-TOPOLOGY-BOUNDED-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Topology streams minimal trace records, resolves endpoints in time-pruned batches and enforces an aggregation budget.", + "invariant": "Cross-batch inbound and outbound multiplicities preserve the complete graph; budget exhaustion returns an explicit error.", + "verification": [ + "unit", + "integration" + ] + }, + { + "id": "CLICKHOUSE-PAIR-VERSION-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Metadata updates preserve authoritative source versions even if the source clock is ahead.", + "invariant": "Each changed row receives a strictly greater version; exhausted versions fail explicitly and unrelated metadata remains intact.", + "verification": [ + "integration" + ] + }, + { + "id": "CLICKHOUSE-PAIR-INDEX-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Pairing reads a time-ordered versioned candidate index with recoverable recent-window backfill.", + "invariant": "All source versions are mirrored; latest rows are selected before role filtering. Rebuilt indexes and widened windows recover coverage on Atomic and Ordinary, including MV gaps and legacy zero-ID readiness; unchanged generations reuse readiness after restart. Retention uses end time, and recurring scans do not grow with unrelated old history.", + "verification": [ + "integration" + ] + }, + { + "id": "CLICKHOUSE-PAIR-PAGING-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Paged pairing preserves complete fingerprint clusters and existing classifier semantics.", + "invariant": "Equal-time keys and transitive clusters survive page boundaries; overlap catches late unmatched members. Resource exhaustion fails explicitly before incomplete groups are written.", + "verification": [ + "unit", + "integration" + ] + }, + { + "id": "CLICKHOUSE-PAIR-REPAIR-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-clickhouse", + "requirement": "Partial metadata batches replay the durable original group and patches after failure or restart.", + "invariant": "Already-tagged and out-of-window members remain in pending repair; fresh rows preserve unrelated metadata, missing rows stay deleted, and exact targets avoid gratuitous writes.", + "verification": [ + "unit", + "integration" + ] + }, + { + "id": "PAIR-SWEEPER-HOOK-001", + "tier": 1, + "priority": "P1", + "module": "h-storage", + "requirement": "A backend-owned pairing sweep can replace the shared fallback without changing shutdown and checkpoint behavior.", + "invariant": "Handled sweeps bypass legacy queries and hook errors propagate without fallback; other backends retain their existing path.", + "verification": [ + "unit" + ] + }, { "id": "AGLAKE-RETRY-413-001", "tier": 0, @@ -207,6 +288,106 @@ "verification": [ "e2e" ] + }, + { + "id": "PROTO-STREAM-INTEGRITY-001", + "tier": 0, + "priority": "P1", + "module": "h-protocol", + "requirement": "SSE frames survive UTF-8, chunk, line-ending and capture-EOF boundaries.", + "invariant": "Received frames are preserved in order without duplicate events or replacement characters.", + "verification": [ + "unit" + ] + }, + { + "id": "PROTO-TCP-LIFECYCLE-001", + "tier": 0, + "priority": "P1", + "module": "h-protocol", + "requirement": "TCP half-close and out-of-order FIN preserve the opposite direction and missing bytes.", + "invariant": "A response closes once its own contiguous bytes reach FIN; retransmitted FIN cannot close both directions.", + "verification": [ + "unit" + ] + }, + { + "id": "LLM-STREAM-EVIDENCE-001", + "tier": 1, + "priority": "P1", + "module": "h-llm", + "requirement": "Chat and Responses streams retain provider errors and partial output.", + "invariant": "Provider terminal state is authoritative; a missing terminal never invents successful completion.", + "verification": [ + "unit" + ] + }, + { + "id": "TURN-COMPACT-001", + "tier": 1, + "priority": "P1", + "module": "h-turn", + "requirement": "Pending turns keep grouping evidence without owning full request or response payloads.", + "invariant": "Releasing the stored call releases its payload while turn previews, identity and PID fallback remain correct.", + "verification": [ + "unit" + ] + }, + { + "id": "TURN-ACTIVE-LIFECYCLE-001", + "tier": 1, + "priority": "P1", + "module": "h-turn", + "requirement": "Active snapshots follow their represented partition through completion, discard, idle, drain and tracker exit.", + "invariant": "Retired partitions leave no ghost snapshot; surviving tails keep the correct ID and shared trackers remove only their own entries.", + "verification": [ + "unit" + ] + }, + { + "id": "TURN-INCREMENTAL-001", + "tier": 1, + "priority": "P1", + "module": "h-turn", + "requirement": "Ordered long-turn ingestion updates snapshots incrementally without whole-buffer or whole-session rescans.", + "invariant": "Every Trace field matches reference assembly, including stable equal-time order, while deterministic work grows linearly on ordered streams.", + "verification": [ + "unit" + ] + }, + { + "id": "DUCKDB-JOURNAL-001", + "tier": 0, + "priority": "P0", + "module": "h-storage-duckdb", + "requirement": "Journal mode durably appends deduplicated payloads before asynchronous metadata indexing.", + "invariant": "Replay commits its cursor with indexed rows, survives restart and index failure, and hydrates exact payloads on detail reads.", + "verification": [ + "integration", + "fault" + ] + }, + { + "id": "STORAGE-DRAIN-001", + "tier": 0, + "priority": "P0", + "module": "h-storage", + "requirement": "Durable sink and maintenance shutdown finish pending writes and surface failures.", + "invariant": "Append, index and final-checkpoint failures reach supervision instead of reporting a successful drain.", + "verification": [ + "fault" + ] + }, + { + "id": "DUCKDB-RESOURCES-001", + "tier": 0, + "priority": "P1", + "module": "h-storage-duckdb", + "requirement": "DuckDB resource settings reach the database and checkpoint waits for active writers.", + "invariant": "Configured worker, memory, reader and allocator limits are applied without losing an in-flight commit.", + "verification": [ + "unit" + ] } ] }