← Back to Pull requests

Fix SQL span summaries for multi-line queries and CTEs #2958

Closed
unknown closed this pull request without merging on Nov 30, 2026 11:04 UTC
View on GitHub
unknown unknown commented on Nov 27, 2026 19:56 UTC
Author

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).
  • <!-- This is an auto-generated description by cubic. -->
    <a href="https://cubic.dev/pr/pydantic/logfire/pull/2958?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
    <!-- End of auto-generated description by cubic. -->

    Diff: 410 lines (+307 / -103) across 5 files Reviewer: chrikrah Review duration: 3787m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.45) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.45 · 410 lines diff across 5 files
    0.45
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.360
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #2958"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 44.9% (MEDIUM) · Higher = larger blast radius
    44.9%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.7% · Safe to merge
    17.7%