Skip to content

Search the whole request history, including request and answer text - #245

Merged
fylorn merged 2 commits into
mainfrom
history-search
Oct 1, 2026
Merged

fylorn merged 2 commits into
mainfrom
history-search

Conversation

@fylorn

@fylorn fylorn commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

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. With content: true it 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

  • Filters reproduce Lite's filterRows exactly (src/requestTable.ts on dev, plus how useRequests.ts turns a HistoryRow into a row):
    • failed only
    • unpriced only: finished, reported usage, no cost
    • exact client, upstream and model. Local answers have no upstream, as in the UI, so an upstream filter drops them.
    • free text over path, client, client hint, peer, the upstream cell, model and the error text. The text is trimmed the way JS trim() trims and lowercased like toLowerCase(). 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.
  • Paging uses before: {at_ms, id}, taken from the previous page's next. It stays stable when rows share a millisecond. Default 100 rows, at most 500. next: null means the whole range has been searched.
  • Response:
    • rows: the same HistoryRow shape as /history, with security records attached
    • hits: one per content match, with side (request / answer) and before / matched / after. About 40 characters each side, whitespace squeezed, … where the text was cut.
    • next: the cursor. next.at_ms is 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, budget or end
  • POST, not GET. Every other read takes its query in the query string, but serde_urlencoded cannot 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 (rusqlite functions feature, no new crates). It folds case with the same Unicode table as toLowerCase.

Why not LIKE: SQLite's LIKE folds ASCII only, so "Über" would not match "über" or "Яндекс" "яндекс", and % and _ would need escaping. tw_has is a literal substring match, and a test covers %, _ and \.

The query walks requests_at. Ties on at_ms are 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

  • Only what is new in each request. Claude Code resends the whole conversation every time, so the search reads only the request's last user turn: the trailing user messages, with their text and tool results.
  • The answer includes its tool calls. For coding clients the model's action is the tool call (an Edit with code, a Bash command), 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.
    • streams: the arguments exactly as streamed, fragments of one block joined
    • whole responses: the input is already a JSON object there, so it is written as compact JSON with keys sorted (serde_json is built without preserve_order); arguments that are not valid JSON stay as written
    • freeform tools (Codex's apply_patch): the raw text
  • Parsing reuses tw-dialect:
    • requests are decoded to the IR with convert::decode
    • whole answers go through each format's decode_response
    • streams go through convert::Reader, including Bedrock's SSE-transcoded stream and Gemini's JSON-array stream
    • the upstream format comes from the row's translated column, otherwise from the client path
  • Escapes and case: \uXXXX text decodes to the real characters, so a Chinese query finds Python-escaped bodies. Comparison is case-insensitive.
  • Two decoding adjustments:
    • Server-state references make tw-dialect refuse conversion: previous_response_id, compaction, item_reference, cachedContent. They are stripped first so those requests still yield their last turn.
    • Tool definitions and the history before the last assistant message are dropped before decoding. This is cheaper and gives the same answer.
  • Raw-byte prefilter. Request bodies and whole JSON answers are prefiltered on raw bytes before parsing:
    • an ASCII alphanumeric run of the query, matched case-insensitively
    • or a run of caseless characters, as UTF-8 or \uXXXX
    • the only two characters whose lowercase is ASCII (U+0130, U+212A) are handled explicitly
    • streams are not prefiltered, because a word can be split across deltas
  • Only generation calls are read. A count_tokens request carries the same conversation as the next request and would duplicate its hit. The path mapping copies tw_gateway::client_api::ClientApi::of_path plus generates, since tw-store cannot depend on the gateway. A tw-control test checks the two agree path by path.
  • Budget. Each call reads at most 500 requests' bodies or runs 1.5 s, newest first, whichever comes first. Then it returns 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.
  • Locking. Bodies are read without the recorder lock. The lock is taken once per batch of 64 rows, so recording is not blocked for the length of a search. The whole search runs on spawn_blocking.

How it was verified

  • cargo fmt --all -- --check: clean
  • cargo clippy --workspace --all-targets -- -D warnings: clean
  • env -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspace on 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)
  • TypeScript, the CI steps:
    • cargo clippy -p tw-api --all-targets --features ts -- -D warnings and cargo test -p tw-api --features ts: clean
    • export_ts, then tsc --noEmit --strict --target es2022: OK
  • scripts/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:
    • a content search for the smoke run's "我的 key 是 sk-ant-api03-SMOKEKEY…" request returns masked excerpts
    • a query that only occurs inside that key finds nothing
  • New tests:
    • parity: a literal Rust port of filterRows and mergeHistory is 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 \.
    • paging: cursors over rows sharing timestamps at page sizes 1–20; limits 100 / 500 / 1; time windows; the query plan
    • content: all four formats (plus Bedrock), streamed and whole; \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 answer
    • tool calls: text and tool calls in block order for every format on both paths, including Responses custom_tool_call and arguments joined across deltas; thinking excluded in each; non-JSON arguments kept as written; "npm install" found from a streamed Bash call and from a whole Chat response; a key inside a tool call masked in the excerpt
    • budget: continuation across calls by count and by time; full pages
    • pruned bodies: still found by metadata and not counted against the budget
    • masking: excerpts are masked, including a key straddling the mask window; hits only inside a secret are dropped
    • paths: the store and gateway read paths the same way
    • HTTP shape: the endpoint through the router

Measured (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:

    Query Per request
    ASCII word found nowhere ~0.5 ms
    Chinese word found nowhere ~0.65 ms
    word in every raw body (first turn of a session), so each such request is fully parsed ~1.4 ms

    Reproduce with: cargo test --release -p tw-store content_search_cost -- --ignored --nocapture

    A 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

  • Tool inputs are searched as JSON text. A quote or newline inside an argument appears escaped (\", \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.
  • Error text in a non-English UI. The English error text is matched as well as the codes the UI sends. A Chinese UI searching an English word that appears in the English sentence will also match. The args are shared and are the useful part.
  • Unreadable bodies. A truncated request body (over 4 MB) or a truncated whole JSON answer (over 256 KB) does not parse, so it is skipped by content search. Streams up to the cut are still read.
  • No cancellation. A search runs to its budget (≤1.5 s) even if the client goes away. Cancel-on-drop is easy to add if the UI aborts stale searches.
  • What is not touched: CONTROL_API_VERSION, the store SCHEMA and crate versions are unchanged. No message codes were added; failures reuse control.store_unavailable, control.records_unreadable and control.internal_error.

Protocol note for the CONTROL_API_VERSION comment

Adds POST /history/search (HistorySearchQuery → HistorySearchPage). It searches the whole request history with the Traffic page's filter (failed, unpriced, client, upstream, model, free text, plus error_codes and local_matches for what the UI shows in its own language). It pages back by a HistoryCursor {at_ms, id}. With content: true it 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, and stopped (full / budget / end), next and bodies_since_ms say 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

fylorn and others added 2 commits October 1, 2026 19:12
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>
@fylorn
fylorn merged commit 877b315 into main Oct 1, 2026
4 checks passed
@fylorn
fylorn deleted the history-search branch October 1, 2026 11:34
@fylorn fylorn mentioned this pull request Oct 1, 2026
fylorn added a commit that referenced this pull request Oct 1, 2026
Release for #244, #245 and #246.

- Bump the workspace version to 0.57.0
- Control-plane protocol 30 -> 31, with the version comment for the
  upstream check-up, history search and the personal-number matchers
- release-notes/0.57.0.md

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant