Repository navigation
Search the whole request history, including request and answer text - #245
Merged
Merged
Conversation
The Traffic page filters only the rows it loaded (the latest 2000), while the store keeps request rows for 90 days. This adds POST /history/search, which runs the same filter in the store and pages back through all of it. - Filters reproduce Lite's filterRows exactly: failed only, unpriced only (finished, reported usage, no cost), exact client / upstream / model, and a free-text query over path, client, client hint, peer, upstream, model and the error text. Error codes whose translation contains the query and a flag for the UI's "answered locally" sentence cover what the UI shows in its own language. - Matching runs in SQL through a small `tw_has()` function with the same Unicode lowercasing as JavaScript's toLowerCase (SQLite's LIKE folds ASCII only and treats % and _ as wildcards). It walks the at_ms index: 100k rows with no match take ~32 ms in a release build. - Pages are cursored by (at_ms, id), stable when rows share a timestamp; default 100 rows, at most 500. - Content search (`content: true`) also looks at the last user turn of each request (text and tool results, not the resent history) and the text of the answer, parsed with tw-dialect for all formats, streamed or whole. Each call reads at most 500 requests' bodies or runs 1.5 s, then returns what it found with a cursor to continue; rows older than the oldest body directory are matched by their record only. Content hits carry a short excerpt, masked like the request detail view. No schema change; CONTROL_API_VERSION and crate versions are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
For coding clients the model's actual action is the tool call: an Edit with code, a Bash command. Content search now reads each tool call of the answer as its name and input text, one per line, in block order with the text: the arguments as streamed (fragments of a block joined), or as a compact JSON object for whole responses, and the raw text of freeform tools such as apply_patch. Reasoning stays out. Excerpts from tool calls are masked like the rest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
What this changes
New control-plane endpoint
POST /history/search(HistorySearchQuery→HistorySearchPage). It runs the Traffic page's filter in the store and pages back through the whole request history. Withcontent: trueit also searches the text of each request's last user turn, and the answer's text and tool calls.Why
The Traffic page calls
GET /history(newest 2000 rows) and filters in the UI. So a search only ever sees the latest 2000 requests, while the store keeps rows for 90 days (retention.row_days) and bodies for 7 (retention.body_days).The endpoint
filterRowsexactly (src/requestTable.tsondev, plus howuseRequests.tsturns aHistoryRowinto a row):trim()trims and lowercased liketoLowerCase(). Peer is matched as-is, like the UI.error_codes: the UI sends the codes whose translation contains the query, so errors match in its language.local_matches: the UI says whether its "answered locally" sentence contains the query, so local answers match too.before: {at_ms, id}, taken from the previous page'snext. It stays stable when rows share a millisecond. Default 100 rows, at most 500.next: nullmeans the whole range has been searched.rows: the sameHistoryRowshape as/history, with security records attachedhits: one per content match, withside(request/answer) andbefore/matched/after. About 40 characters each side, whitespace squeezed,…where the text was cut.next: the cursor.next.at_msis how far back this call got.bodies_since_ms: the oldest body day on disk, so the UI can say content before it is gone.stopped:full,budgetorendserde_urlencodedcannot carry a list (error_codes). Read endpoints with structured input already use POST (/pricing/query,/dryrun, the quotes).Metadata matching
The filters run in SQL over
requests. The text match is a small SQL function,tw_has(field, q), registered on every connection (rusqlitefunctionsfeature, no new crates). It folds case with the same Unicode table astoLowerCase.Why not
LIKE: SQLite'sLIKEfolds ASCII only, so "Über" would not match "über" or "Яндекс" "яндекс", and%and_would need escaping.tw_hasis a literal substring match, and a test covers%,_and\.The query walks
requests_at. Ties onat_msare ordered by a per-millisecond block sort ("USE TEMP B-TREE FOR LAST TERM OF ORDER BY"), not a sort of the whole table. A test checks the plan for every shape of the statement. No schema change.Content search
Editwith code, aBashcommand), so "the request where it ran npm install" is found. Each tool call is one line: name, a space, then the input. Text blocks and tool calls appear in block order. Reasoning stays out.preserve_order); arguments that are not valid JSON stay as writtenapply_patch): the raw textconvert::decodedecode_responseconvert::Reader, including Bedrock's SSE-transcoded stream and Gemini's JSON-array streamtranslatedcolumn, otherwise from the client path\uXXXXtext decodes to the real characters, so a Chinese query finds Python-escaped bodies. Comparison is case-insensitive.previous_response_id,compaction,item_reference,cachedContent. They are stripped first so those requests still yield their last turn.\uXXXXcount_tokensrequest carries the same conversation as the next request and would duplicate its hit. The path mapping copiestw_gateway::client_api::ClientApi::of_pathplusgenerates, since tw-store cannot depend on the gateway. A tw-control test checks the two agree path by path.stopped: "budget"with the cursor. Rows older than the oldest body directory are not probed one by one; they go straight to the metadata SQL.spawn_blocking.How it was verified
cargo fmt --all -- --check: cleancargo clippy --workspace --all-targets -- -D warnings: cleanenv -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspaceon the branch rebased onto main (after Redact Chinese resident ID and bank card numbers out of the box #244): 1995 passed, 0 failed, 5 ignored (1 new: the content benchmark below)cargo clippy -p tw-api --all-targets --features ts -- -D warningsandcargo test -p tw-api --features ts: cleanexport_ts, thentsc --noEmit --strict --target es2022: OKscripts/smoke.sh: 65 passed, 0 failed. The one ⚠ is the existing memory warning tier (37–38 MB against a 30 MB target). Two new smoke checks run against the real binary:filterRowsandmergeHistoryis the reference. It is compared against the endpoint over a 120-row matrix: failed, cancelled, unpriced, no-usage, local (including token-count estimates that keep an upstream name), LAN peers, uppercase non-ASCII names. That is 24 queries × 10 filter combinations. Also covered: error codes, local answers, literal%,_and\.\u-escaped Chinese in requests and streams; only the last turn of a long conversation; prefill; a word split across SSE deltas; translated answers read in the upstream format; request side preferred over the answercustom_tool_calland arguments joined across deltas; thinking excluded in each; non-JSON arguments kept as written; "npm install" found from a streamedBashcall and from a whole Chat response; a key inside a tool call masked in the excerptMeasured (release build, Apple Silicon)
Metadata: 100,000 rows, a query matching nothing: ~32 ms (debug build: ~123 ms). First page of a common match: ~1 ms.
Content: synthetic Claude Code sessions, 300 requests, 169 MB of bodies (requests average ~560 KB, answers ~50 KB of SSE with thinking, text and tool_use). Including tool calls in the answer did not change these:
Reproduce with:
cargo test --release -p tw-store content_search_cost -- --ignored --nocaptureA full 500-body budget is therefore typically about 0.3–0.7 s. The 1.5 s cap covers multi-MB bodies and slow disks.
Credentials. Excerpts are masked with
tw_secret::mask_body, the same as the request detail drawer. Masking runs on a window around the hit that is widened to token boundaries, so it masks exactly as masking the whole text would. A hit that exists only inside a credential is dropped and the search moves to the next occurrence. Nothing else returned contains body text.Notes for review
\",\n), so search for a value (npm install) rather than code containing quotes. Whole responses re-serialize the input compactly, so spacing may differ from the streamed form.CONTROL_API_VERSION, the storeSCHEMAand crate versions are unchanged. No message codes were added; failures reusecontrol.store_unavailable,control.records_unreadableandcontrol.internal_error.Protocol note for the
CONTROL_API_VERSIONcommentAdds
POST /history/search(HistorySearchQuery→HistorySearchPage). It searches the whole request history with the Traffic page's filter (failed, unpriced, client, upstream, model, free text, pluserror_codesandlocal_matchesfor what the UI shows in its own language). It pages back by aHistoryCursor{at_ms, id}. Withcontent: trueit also searches, for requests whose bodies are still on disk, the last user turn and the answer (its text and tool calls, name plus input), returning masked excerpts (ContentHit). Each call is budgeted, andstopped(full/budget/end),nextandbodies_since_mssay how far it got. New types:HistorySearchQuery,HistoryCursor,HistorySearchPage,ContentHit,ContentSide,SearchStop. Purely additive: a UI written for the previous version just does not see the endpoint.🤖 Generated with Claude Code