Skip to content

fix(db_statement_summary): bound INSERT summary length like the SELECT path - #2084

Merged
dmontagu merged 4 commits into
pydantic:mainfrom
chuenchen309:fix/insert-summary-length-bound
Aug 12, 2026
Merged

dmontagu merged 4 commits into
pydantic:mainfrom
chuenchen309:fix/insert-summary-length-bound

Conversation

@chuenchen309

@chuenchen309 chuenchen309 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

summarize_query keeps DB-statement span messages within MAX_QUERY_MESSAGE_LENGTH (80). The SELECT path enforces this by ending in truncate(summary, MAX_QUERY_MESSAGE_LENGTH), and the fallback path is bounded too — but the INSERT branch returned its f-string directly:

return f'INSERT INTO {table} {truncate(columns, 25)} VALUES {truncate(values, 25)}'

columns/values are truncated, but table is not, so a long (e.g. schema-qualified) table name pushes the summary past the limit.

Reproduction

>>> from logfire._internal.db_statement_summary import summarize_query
>>> q = 'INSERT INTO "analytics"."very_long_events_table_name_for_testing" (a, b, c, d) VALUES (1, 2, 3, 4)'
>>> len(summarize_query(q))
112   # > MAX_QUERY_MESSAGE_LENGTH (80)

The equivalent SELECT with the same long table stays bounded (~74 chars).

Fix

Wrap the INSERT result in the same final truncate(..., MAX_QUERY_MESSAGE_LENGTH) that the SELECT path already applies, so every branch stays bounded.

Tests

Added test_insert_long_table; the existing test_insert (short table) is unchanged. Full tests/test_db_statement_summary.py passes (24), and ruff format/check + pyright are clean on the touched files.

Review in cubic

…T path

summarize_query is meant to keep span messages within
MAX_QUERY_MESSAGE_LENGTH (80). The SELECT branch enforces this with a
final truncate(summary, MAX_QUERY_MESSAGE_LENGTH), but the INSERT branch
returned its f-string directly. Since the table name is not truncated on
its own, a long (e.g. schema-qualified) table produced summaries well
over the limit (112 chars in the added test), unlike SELECT and the
fallback path. Wrap the INSERT result in the same final truncate so it
stays bounded.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@dmontagu, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 27 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d5ff65e-3f41-4420-ac80-742a53f35272

📥 Commits

Reviewing files that changed from the base of the PR and between 2156578 and b8a2640.

📒 Files selected for processing (2)
  • logfire/_internal/db_statement_summary.py
  • tests/test_db_statement_summary.py
📝 Walkthrough

Walkthrough

INSERT query summaries now apply the shared truncate function to the complete generated message, enforcing MAX_QUERY_MESSAGE_LENGTH after composing the table, columns, and values. A regression test covers an INSERT statement with a long schema-qualified table name and verifies that the returned summary remains within the configured limit.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: bounding INSERT summaries like the SELECT path.
Description check ✅ Passed The description matches the change set and explains the INSERT truncation fix and regression test.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@logfire/_internal/db_statement_summary.py`:
- Around line 82-85: The INSERT summary truncation in truncate must reserve one
character for the ellipsis so the final result never exceeds
MAX_QUERY_MESSAGE_LENGTH. Update logfire/_internal/db_statement_summary.py lines
82-85 accordingly, then revise tests/test_db_statement_summary.py lines 158-168
to assert len(summary) <= MAX_QUERY_MESSAGE_LENGTH and update the expected
literal for the corrected output.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8232872b-3d75-4136-88b1-5479f41f1aee

📥 Commits

Reviewing files that changed from the base of the PR and between db9859a and 60dd04a.

📒 Files selected for processing (2)
  • logfire/_internal/db_statement_summary.py
  • tests/test_db_statement_summary.py
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • pydantic/logfire (manual)
  • pydantic/pydantic-ai (manual)
  • pydantic/platform (auto-detected)
  • pydantic/pydantic (auto-detected)

@codecov

codecov Bot commented Jul 16, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@chuenchen309

Copy link
Copy Markdown
Contributor Author

Good catch that truncate(summary, MAX_QUERY_MESSAGE_LENGTH) can return MAX + 1 chars — but that's a property of the shared truncate() helper, not something this PR introduces: for an even length, truncate returns 2 * (length // 2) + 1 (so 80 → 81). The main/SELECT path already bounds its summary the exact same way (return truncate(summary, MAX_QUERY_MESSAGE_LENGTH)), so wrapping the INSERT branch in the same helper keeps the two paths consistent — which is the point of this fix (the INSERT summary was previously unbounded at ~112 chars).

Making the INSERT result strictly <= MAX while the SELECT path stays at MAX + 1 would introduce an inconsistency. The clean way to get a hard <= MAX guarantee is to fix truncate itself (e.g. half_length = (length - 1) // 2), but that changes every even-length caller (10, 80) and their existing snapshots, which is out of scope for "bound the INSERT summary." Happy to do that as a follow-up if you'd prefer the strict bound.

…itly

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Re-trigger cubic

@chuenchen309

Copy link
Copy Markdown
Contributor Author

Putting a number on the "out of scope" claim I made above, since it was an assertion and this is checkable:

Applying the suggested truncate change (reserving one character for …, i.e. half_length = (length - 1) // 2) fails 9 of the 24 tests in tests/test_db_statement_summary.py — test_long_select, test_one_join_long and friends, all of which pin exact 81-character SELECT output that predates this PR.

That's the reason this PR leaves truncate alone: the 81-vs-80 is a property of truncate itself (f'{s[:length // 2]}…{s[-(length // 2):]}' → 2 * (length // 2) + 1), shared by the SELECT path that already calls it. This PR only makes the INSERT branch honour the same bound the SELECT branch already honours; tightening truncate would change every existing SELECT summary and is a separate, deliberate decision.

Happy to send that as its own PR if the team wants the bound to be exact — it'd need the expected literals in those 9 tests updated too.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Comment thread tests/test_db_statement_summary.py Outdated
def test_insert_long_table():
# The table name isn't truncated on its own, so this was 112 chars before the bound.
q = 'INSERT INTO "analytics"."very_long_events_table_name_for_testing" (apple, banana, carrot, durian, egg, fig) VALUES (1, 2, 3, 4, 5, 6)'
# insert_assert(message_from_db_statement(attrs(q), None, 'INSERT'))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather use inline_snapshot

table, columns, values = insert_match.groups()
return f'INSERT INTO {table} {truncate(columns, 25)} VALUES {truncate(values, 25)}'
return truncate(
f'INSERT INTO {table} {truncate(columns, 25)} VALUES {truncate(values, 25)}',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rather truncate table

Address review feedback: rather than truncating the whole composed
message (which produced a second ellipsis in the middle of the column
list), truncate the `table` component the way `columns` and `values`
already are. The table gets whatever length is left over from
MAX_QUERY_MESSAGE_LENGTH, since it's the best identifier of the query,
so it's only shortened when the message would actually overflow.

Use inline_snapshot for the new tests.
@dmontagu

Copy link
Copy Markdown
Contributor

Hi @chuenchen309 — thanks for catching this and for the clear write-up and repro. I hope you don't mind: I pushed a commit directly to your branch applying @alexmojaki's two review suggestions, so this can move forward without more round-trips.

What changed:

  • Truncate table rather than the whole message. Wrapping the composed f-string meant the summary got a second ellipsis dropped into the middle of the column list (INSERT INTO "analytics"."very_long_event…a…n, egg, fig) VALUES …). Now table is truncated as its own component, the way columns and values already are. It gets whatever length is left over from MAX_QUERY_MESSAGE_LENGTH after the columns and values, since the table is the best identifier of the query — so it is only shortened when the message would actually overflow, and short table names are never touched:

    INSERT INTO "analyti…testing" (apple, bana…n, egg, fig) VALUES (1, 2, 3, 4, 5, 6)
    INSERT INTO "analytics"."ve…me_for_testing" (apple) VALUES (12345678901234567890)
    
  • inline_snapshot for the new tests, replacing the hand-written expected strings.

Your reasoning on the CodeRabbit truncate() off-by-one was right, and I left the shared helper alone — the INSERT path now has exactly the same bound characteristics as the SELECT path, which was the goal of the PR. The explicit length assertion went away with the snapshot rewrite, since any regression in the bound would change the snapshotted string anyway.

test_insert and every other existing expectation are unchanged; 25 passed locally, plus the sqlalchemy/mysql/sqlite3 integration tests, and ruff + pyright are clean.

@dmontagu
dmontagu added this pull request to the merge queue Aug 12, 2026
Merged via the queue into pydantic:main with commit d9e4fb7 Aug 12, 2026
31 of 33 checks passed
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.

3 participants