Fix SQL span summaries for multi-line queries and CTEs

Closed
AL
3d ago
+84-15

Summary

Fixes two issues in logfire-sdk/logfire/_internal/db_statement_summary.py:

  1. Multi-line or space-padded CTE queries matched the inner SELECT instead of the outer SELECT:
    After collapsing whitespace, WITH active_users AS (\n SELECT ... became WITH active_users AS ( SELECT .... SELECT_CTE_RE = re.compile(rf'WITH (.+?) SELECT (.+?) FROM ({TABLE_RE})') then matched the SELECT ... FROM ... inside the first CTE body instead of the main SELECT after the CTE definitions — producing the wrong table name, wrong columns, wrong CTE count, and wrong WHERE … indicator.
  2. Single newlines were not collapsed:
    re.sub(r'\s{2,}', ' ', db_statement) left single \n / \t characters intact, so queries formatted with a single newline between clauses (e.g. SELECT ...\nFROM table) failed SELECT_RE and fell back to fallback().

Replaced re.sub(r'\s{2,}', ' ', ...) with re.sub(r'\s+', ' ', ...) and replaced SELECT_CTE_RE with a linear-time match_cte_select() helper using the same quote/parenthesis depth tracking as outside_parentheses() (which also avoids quadratic regex backtracking in SELECT_CTE_RE).

Minimal runnable reproducer

from logfire._internal.db_statement_summary import message_from_db_statement

q = """
WITH active_users AS (
    SELECT id, email FROM users WHERE active = true
),
recent_orders AS (
    SELECT user_id, total FROM orders WHERE total > 100
)
SELECT * FROM recent_orders
"""
print(message_from_db_statement({'db.statement': q, 'db.system': 'postgresql'}, None, 'SELECT'))
# Before: 'WITH activ…users AS (…) SELECT id, email FROM users WHERE …'
# After:  'WITH …[2 CTEs] SELECT * FROM recent_orders'

Checklist context (CONTRIBUTING.md)

  • Encountered in practice or analytical find: Observed by inspecting and testing standard formatted SQL queries against db_statement_summary.py; affects any multi-line CTE or unindented multi-line query over 80 chars.
  • Impact on behavior: SQL span messages in the Logfire Live View showed misleading table names, columns, and CTE counts (or truncated fallback text with newlines).
  • Security problem: No.
  • Reviewability / confidence: Small (~30 lines), self-contained in db_statement_summary.py, easy to verify and merge as-is.
  • Performance: Linear single pass over db_statement (and removes SELECT_CTE_RE's two-lazy-group backtracking).

Verification

  • ruff check and ruff format --check passed on both touched files.
  • pytest tests/test_db_statement_summary.py -v passed (33 passed, including 3 new tests covering multi-line CTEs, spaces inside CTE parentheses, and unindented multi-line SELECT).