Skip to content

feat(tracing): find N+1 queries in traces - #386

Closed
roxblnfk wants to merge 5 commits into
masterfrom
feat/trace-insights
Closed

roxblnfk wants to merge 5 commits into
masterfrom
feat/trace-insights

Conversation

@roxblnfk

@roxblnfk roxblnfk commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

🔍 What was changed

  • Traces are checked for N+1 queries: a database query that one transaction runs 5 times or more, up to its values. The trace page's Request view of the bundled UI 1.42 now shows its N+1 hint and groups the spans (n_plus_one in the trace detail).
  • MCP get_trace lists findings between the header and the span tree (rule, span count, total ms, transaction, file:line origin, first span ID, the query with ? for values); list_traces gives each trace a findings count.
  • trap test sends a checkout trace with six repeated product queries.

How it works

  • A small pipeline in Server\Telemetry\Insight: TraceRule → Findings, TraceInsights runs the default rules (one line per rule) and sorts by total duration, then span count. No toggles.
  • Findings are computed on read and cached on the Trace with the pipeline, seq and size: a new span bumps seq, and eviction or clearing a project (which leave seq alone) shrink the size, so the cache never serves a stale trace.
  • QueryShape normalizes in one pass over tokens, so a ?, quote or number inside a literal or comment stays put; table2, "quoted" names and ::casts stay, IN/VALUES lists collapse, sqlcommenter comments go.

Review notes

  • Differs from the Go server on purpose: the query comes from db.query.text / db.statement before the description (an OTel span name is only SELECT shop.products), OTLP and Sentry v2 spans are assigned to their transaction up the parent chain, and findings are ordered by time spent rather than count.
  • Literals follow the dialect from db.system / db.system.name: backslash escapes for MySQL/MariaDB and E'…', standard strings elsewhere; with no dialect a backslash escapes unless the literal would then never end. "…" is an identifier, never a string. # is not a comment (it is an operator in Postgres).
  • Shaping reads the first 32 KB of a query and nests lists at most 32 deep, so a 1 MB query costs a few ms on the loop; Redis and NoSQL db.* spans don't count.

Checklist

  • How was this tested:
    • Unit tests added
    • Full Testo run: green except the known ProtobufCasterTest failures of this machine
    • psalm (only the known Run.php signal errors of Windows), structarmed, markdownlint
    • Tested manually: bin/trap --ui --mcp plus bin/trap test, the N+1 hint on the Request view in headless Chromium, list_traces and get_trace over MCP HTTP

Documentation

  • docs/web-ui.md (new "Repeated queries (N+1)" section), docs/mcp.md, docs/opentelemetry.md; skill references/mcp.md and the SKILL.md route.

…page and findings over MCP

The bundled UI 1.42 shows an N+1 hint on the Request view of a trace when the trace detail carries `n_plus_one`; Trap sent none. Traces now go through a small rule pipeline in `Server\Telemetry\Insight`: a `TraceRule` returns `Finding`s (rule, transaction, span IDs, summary, count, total ms, origin), and `TraceInsights` runs the default rules and sorts the findings by total duration, then span count. The first rule, `n_plus_one`, reports a database query that one transaction runs 5 times or more, up to its values. The query is `db.query.text`, else `db.statement`, else the span description, so OpenTelemetry spans count by their query rather than their short name; a span without a transaction of its own, as an OTLP or a Sentry v2 span, belongs to the transaction up its parents. Durations are summed to a microsecond, and the origin is `code.filepath:code.lineno` (or `code.file.path:code.line.number`) of the first span that has it.

`QueryShape` normalizes a query in one pass over its tokens instead of regular expressions over the text, so a `?`, a number or a quote inside a string literal or a comment stays there: literals (with `''` and `\'` escapes, `E'…'`, `$$…$$`), numbers, booleans and the placeholders `?`, `?1`, `$1`, `:name` become `?`, a `::type` cast and the digits of a name such as `table2` stay, an `IN` list and `VALUES` rows of values become one `(?)`, comments go (a sqlcommenter `traceparent` no longer splits a group), keywords are upper-cased and spacing is made uniform.

Findings are computed when a trace is read and kept on the `Trace` with the pipeline, its `seq` and its size, so they serve every read until a span arrives, and eviction or clearing a project, which leave `seq` alone, drop the cache by the size. The trace page gets `n_plus_one`; `get_trace` lists the findings between its header and the tree, so a cut text keeps them; `list_traces` gives each trace a `findings` count. `trap test` sends a checkout trace with six repeated product queries.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added enhancement New feature or request tests Changes in the tests labels Nov 24, 2026
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.20767% with 15 lines in your changes missing coverage. Please review.
✅ Project coverage is 81.87%. Comparing base (5cb5927) to head (4226427).

Files with missing lines Patch % Lines
src/Server/Telemetry/Insight/Finding.php 0.00% 9 Missing ⚠️
src/Server/Telemetry/Insight/Sql/QueryShape.php 97.75% 4 Missing ⚠️
src/Server/Telemetry/Insight/RepeatedQuery.php 96.87% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #386      +/-   ##
==========================================
+ Coverage   81.64%   81.87%   +0.22%     
==========================================
  Files         462      466       +4     
  Lines       19399    19709     +310     
==========================================
+ Hits        15839    16137     +298     
- Misses       3560     3572      +12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

…t spans, SQL dialects, bounded shaping

- Spans whose transaction has not arrived group under the missing parent they hang from, so the children an OTel batch exports before their server span count together.
- With projects chosen, the rules run over the part of the trace sent to them: count, total and span IDs are of those spans, and a finding below the threshold goes. The trace keeps the findings of each project set it was asked for, at most 16, while it does not change.
- A backslash escapes in a literal of MySQL and MariaDB by `db.system` / `db.system.name`, and in `E'…'`; other databases use standard strings. With no database named, a backslash escapes unless the literal would never end, so `'C:\' AND id = 5` keeps its `AND`.
- `ARRAY[…]` value lists collapse like `IN (…)`, and a sign apart from its number (`x = -  1`) is part of it.
- Only the first 32 KB of a query are shaped, with ` …` after a cut one, a bulk `VALUES` list cut there still collapsing, and lists nest at most 32 deep: a 1 MB query takes 2–5 ms and a million nested brackets 21 ms instead of 0.5 and 2.6 s. Shapes stay with their spans in a `WeakMap`, so a growing trace shapes only its new spans.
- Only SQL spans count: Sentry `db.redis` and spans of Redis, MongoDB and other NoSQL stores by `db.system` are left out.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
…eral scan for an unknown database

- The findings cache of a trace is keyed by `p:` and the project set, and the oldest entry above 16 goes by its key: a key of digits (project `1`) was an int that `array_shift()` renumbered, so a project could get the findings of another.
- With no `db.system`, a query is read with backslash escapes, and read again without them only when a literal then never ends: the escape mode holds for the whole query, which takes linear time (`'\` repeated 20 000 times: 16 ms, was 1.6 s) and gives `'C:\' AND name = 'y'` its two literals.
- A minus after `END` is binary; ClickHouse, Hive, Spanner (`spanner`, `gcp.spanner`), BigQuery, Spark and Databricks take backslash escapes too.
- Docs: queries that differ only after their first 32 KB count as one.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
…collision-free project sets

- With no `db.system`, a literal that runs into the 32 KB cut no longer counts as never ending, so a cut bulk insert keeps the backslash escapes it was read with: `VALUES ('it\'s', 'q'), …` stays `VALUES (?) …`.
- The sign rule gets the token before rather than the token list: `end()` on the list copied it for every `+` and `-`, which made `a-` × 16 000 take 665 ms (1.3 s read twice); it takes 30–50 ms now. Keywords and operators are looked up by key, and the number scan runs only from a digit, a dot or a sign.
- Backslash escapes are kept to the OTel names `mysql`, `mariadb`, `clickhouse`, `hive`, `spanner`, `gcp.spanner`.
- The findings cache keys a project set by its JSON, sorted as strings, so `["a\0b"]` and `["a", "b"]` differ.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
… an unknown one

- A database outside the known lists takes the path of an unnamed one: a backslash escapes unless a literal of the query then never ends. Backslash escapes stay for `mysql`, `mariadb`, `clickhouse`, `hive`, `spanner`, `gcp.spanner`, and now `bigquery` (as the BigQuery client names it) and `snowflake`; standard strings are now kept to `postgresql`, `sqlite`, `mssql`, `microsoft.sql_server`, `oracle`, `oracle.db`, `db2`, `ibm.db2`, `h2`, `h2database`, `derby`, `hsqldb`, `cockroachdb`, `trino`, `firebird`, `firebirdsql`, `teradata`. So `n = 'it\'s' AND id = 5` of `BigQuery` keeps its `AND`.
- The findings cache keys a project set by `serialize()`: JSON substituted invalid UTF-8, so two such names could share findings.
- The timing test compares the time of an input and of four times it, best of five runs: the old copying `numberLength()` gives 14–17 times, linear work under 8.
- Docs: in a query over 32 KB of such a database, a literal that really ends in a backslash takes the rest of the read part.

Assisted-By: Claude Opus 5.5 <noreply@anthropic.com>
@roxblnfk

Copy link
Copy Markdown
Member Author

Landed on master as a fast-forward of one signed commit 709d4d3 (same tree as 4226427).

@roxblnfk roxblnfk closed this Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request tests Changes in the tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant