-
Notifications
You must be signed in to change notification settings - Fork 0
perf: trim the answer payload to what the client renders (round 2, phase 4) #482
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
BigSimmo
merged 1 commit into
claude/perf-r2-auth-roundtrip
from
claude/perf-r2-payload-trim
Jul 11, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import type { RagAnswer, SearchResult } from "@/lib/types"; | ||
|
|
||
| // Route-boundary trim of the answer payload. The retrieval pipeline carries | ||
| // full chunk text plus server-only context on every source (adjacent_context | ||
| // for generation packing, memory cards, table facts, index-unit matches, | ||
| // document summaries), but the client renders only a snippet | ||
| // (retrieval_synopsis ?? content) plus identity, scoring, governance, and | ||
| // label fields. Trimming at the route boundary — never inside rag.ts — keeps | ||
| // caches, generation inputs, and eval behavior byte-identical while cutting | ||
| // the final SSE/JSON event the user waits on after the prose has streamed. | ||
| // | ||
| // Ordering contract: sourceGovernanceWarnings and logAnswerDiagnostics consume | ||
| // the FULL answer and must run before this trim (both routes do). | ||
|
|
||
| // Longest snippet the source cards can usefully show; the render policy falls | ||
| // back to `content` only when `retrieval_synopsis` is absent. | ||
| const clientSourceContentMaxChars = 700; | ||
|
|
||
| function truncateAtWordBoundary(text: string, maxChars: number) { | ||
| if (text.length <= maxChars) return text; | ||
| const slice = text.slice(0, maxChars); | ||
| const lastSpace = slice.lastIndexOf(" "); | ||
| return `${slice.slice(0, lastSpace > maxChars * 0.6 ? lastSpace : maxChars).trimEnd()}…`; | ||
| } | ||
|
|
||
| function trimSourceForClient(source: SearchResult): SearchResult { | ||
| const trimmed: SearchResult = { | ||
| ...source, | ||
| content: truncateAtWordBoundary(source.content ?? "", clientSourceContentMaxChars), | ||
| }; | ||
| delete trimmed.adjacent_context; | ||
| delete trimmed.memory_cards; | ||
| delete trimmed.table_facts; | ||
| delete trimmed.index_unit; | ||
| delete trimmed.document_summary; | ||
| return trimmed; | ||
| } | ||
|
|
||
| export function toClientAnswerPayload<T extends Pick<RagAnswer, "sources">>(answer: T): T { | ||
| if (!answer.sources?.length) return answer; | ||
| return { ...answer, sources: answer.sources.map(trimSourceForClient) }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import { toClientAnswerPayload } from "@/lib/answer-client-payload"; | ||
| import type { RagAnswer, SearchResult } from "@/lib/types"; | ||
|
|
||
| function fullSource(overrides: Partial<SearchResult> = {}): SearchResult { | ||
| return { | ||
| id: "chunk-1", | ||
| document_id: "doc-1", | ||
| title: "Clozapine monitoring guideline", | ||
| file_name: "clozapine.pdf", | ||
| page_number: 4, | ||
| chunk_index: 7, | ||
| section_heading: "Monitoring", | ||
| content: "Full blood count weekly for 18 weeks. ".repeat(60), | ||
| retrieval_synopsis: "FBC weekly for 18 weeks, then monthly.", | ||
| image_ids: [], | ||
| similarity: 0.82, | ||
| source_metadata: { document_status: "current" } as SearchResult["source_metadata"], | ||
| adjacent_context: "Preceding paragraph context. ".repeat(20), | ||
| document_summary: "A long document summary. ".repeat(30), | ||
| memory_cards: [{ id: "m1" } as never], | ||
| table_facts: [{ id: "t1" } as never], | ||
| index_unit: { unit_type: "table" } as never, | ||
| ...overrides, | ||
| } as SearchResult; | ||
| } | ||
|
|
||
| function answerWith(sources: SearchResult[]): Pick<RagAnswer, "sources"> { | ||
| return { sources }; | ||
| } | ||
|
|
||
| describe("toClientAnswerPayload", () => { | ||
| it("drops server-only per-source fields the client never renders", () => { | ||
| const trimmed = toClientAnswerPayload(answerWith([fullSource()])).sources![0]; | ||
| expect(trimmed.adjacent_context).toBeUndefined(); | ||
| expect(trimmed.memory_cards).toBeUndefined(); | ||
| expect(trimmed.table_facts).toBeUndefined(); | ||
| expect(trimmed.index_unit).toBeUndefined(); | ||
| expect(trimmed.document_summary).toBeUndefined(); | ||
| }); | ||
|
|
||
| it("keeps identity, snippet, scoring, and governance fields intact", () => { | ||
| const trimmed = toClientAnswerPayload(answerWith([fullSource()])).sources![0]; | ||
| expect(trimmed.id).toBe("chunk-1"); | ||
| expect(trimmed.title).toBe("Clozapine monitoring guideline"); | ||
| expect(trimmed.retrieval_synopsis).toBe("FBC weekly for 18 weeks, then monthly."); | ||
| expect(trimmed.similarity).toBe(0.82); | ||
| expect(trimmed.source_metadata).toEqual({ document_status: "current" }); | ||
| expect(trimmed.page_number).toBe(4); | ||
| }); | ||
|
|
||
| it("truncates long chunk content at a word boundary", () => { | ||
| const trimmed = toClientAnswerPayload(answerWith([fullSource()])).sources![0]; | ||
| expect(trimmed.content.length).toBeLessThanOrEqual(701); | ||
| expect(trimmed.content.endsWith("…")).toBe(true); | ||
| // Word-boundary cut: no partial trailing token before the ellipsis. | ||
| expect(trimmed.content.at(-2)).not.toBe(" "); | ||
| }); | ||
|
|
||
| it("leaves short content untouched", () => { | ||
| const short = fullSource({ content: "Short snippet." }); | ||
| expect(toClientAnswerPayload(answerWith([short])).sources![0].content).toBe("Short snippet."); | ||
| }); | ||
|
|
||
| it("does not mutate the original answer (caches keep the full sources)", () => { | ||
| const source = fullSource(); | ||
| const answer = answerWith([source]); | ||
| toClientAnswerPayload(answer); | ||
| expect(answer.sources![0].adjacent_context).toBeTruthy(); | ||
| expect(answer.sources![0].content.length).toBeGreaterThan(700); | ||
| }); | ||
|
|
||
| it("passes through answers without sources", () => { | ||
| const empty = answerWith([]); | ||
| expect(toClientAnswerPayload(empty)).toBe(empty); | ||
| }); | ||
|
|
||
| it("materially shrinks a representative payload", () => { | ||
| const answer = answerWith(Array.from({ length: 8 }, (_, index) => fullSource({ id: `chunk-${index}` }))); | ||
| const fullBytes = JSON.stringify(answer).length; | ||
| const trimmedBytes = JSON.stringify(toClientAnswerPayload(answer)).length; | ||
| expect(trimmedBytes).toBeLessThan(fullBytes * 0.5); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When an answer source is longer than 700 chars, this replaces
source.contentbefore it reaches the browser. The dashboard still computes safety findings fromanswer.sources[].content(src/lib/clinical-safety.ts:117-119, called fromClinicalDashboard.tsx:2771), not just snippets; if the only contraindication/dose-limit/monitoring phrase is past the cutoff and no quote card duplicates it, the Safety findings panel drops that warning. A focused test that runstoClientAnswerPayloadbeforeextractSafetyFindingswith a phrase after char 700 would reproduce it.Useful? React with 👍 / 👎.