Fix O(n²) performance in ReindentFilter for large queries#18
Open
Fix O(n²) performance in ReindentFilter for large queries#18
Conversation
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.
38d7d6d to
6da15e1
Compare
Adds 11 benchmark tests covering the query types from the PR
performance tables. Each test generates a deterministic SQL query
and measures sqlparse.format(sql, reindent=True).
Run with:
uv run --with pytest --with pytest-benchmark pytest tests/test_benchmarks.py -v
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Two independent O(n²) bottlenecks in the reindent filter caused format operations to take >300s or time out entirely on 1MB SQL queries. Replace _get_offset's _flatten_up_to_token (which flattened the entire statement from the beginning for every token) with a backward tree walk that only examines tokens on the current line — O(line_length) instead of O(statement_length). Eliminate token_index/list.index calls in _process_identifierlist by pre-computing a token-to-index mapping and tracking insertion shifts, avoiding O(n) linear scans per insert_before call. Results on 1MB queries vs prior branch: - wide_select format: >300s timeout → 8s - large_in_list format: 144s → 9s (16x) - large_insert format: 69s → 5s (15x) - deep_subqueries format: 36s → 14s (2.6x) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
_process_values had two per-iteration O(n) calls that made it O(n²) for large INSERT VALUES: 1. insert_before(ptoken, ...) / insert_after(ptoken, ...) passed token objects, triggering token_index() linear scan. Fixed by passing the integer index (ptidx) already available from token_next_by(). 2. _get_offset(token) called _reverse_leaves_before which did parent.tokens.index(current) on the Values group. Fixed by adding an optional _parent_idx hint so the backward walk skips the O(n) index() call on the hot parent. Also hoists _get_offset(first_token) out of the loop in comma_first mode since the value is loop-invariant. Before: 5k rows 30s, 10k rows 87s (quadratic) After: 5k rows 1s, 10k rows 3s, 25k rows 6s (linear) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
6da15e1 to
3326190
Compare
stevephodgson
requested changes
Feb 25, 2026
Rename _parent_idx to known_parent_and_idx for clarity and remove unnecessary comment in _process_values per reviewer feedback. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
stevephodgson
approved these changes
Feb 25, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
After reviewing #16, I set claude loose on the repo and asked it to stress test other forms of large queries to look for similar cases. And it found 3. The issues and fixes are described below. I also had it added
pytest-benchmarkbenchmarks for a bunch of cases and report the speedups.Summary
Fix O(n²) performance bottlenecks in
ReindentFilterthat causesqlparse.format(..., reindent=True)to hang on large SQL queries. After these fixes, the same queries format in seconds.This is a companion to #16 which fixes parse-time O(n²) in
group_tokens. This branch fixes the remaining format-time O(n²) in the reindent filter.Changes
Fix 1: Replace
_get_offsetwith backward tree walk_flatten_up_to_tokenconcatenated all tokens from the start of the statement, then tooksplitlines()[-1]to get the current line — O(statement_length) per call_reverse_leaves_beforeand_reverse_flattenfor the backward walk_flatten_up_to_tokenmethodFix 2: Eliminate
token_indexcalls in_process_identifierlistinsert_before(token, ...)calledtoken_index(token)→list.index(token)= O(n) linear scan per insertion{id(token): index}mapping once, pass integer indices directly toinsert_before/insert_after, and track cumulativeshiftfrom insertionsFix 3: Eliminate O(n²) in
_process_valuesfor large INSERT statementstoken_next_bydirectly. Added_parent_idxhint parameter so the backward walk skips the O(n)index()call on the hot parent. Hoisted loop-invariant offset incomma_firstmode.Benchmark Results
Reproducible benchmark tests are included in the first commit (
tests/test_benchmarks.py). Run with:Reindent benchmarks
SELECT col_0, col_1, ... col_4999 FROM tSELECT * FROM t WHERE id IN (0, 1, ... 99999)INSERT INTO t VALUES (0, 1), (1, 2), ... (24999, 25000)SELECT * FROM (SELECT * FROM (... FROM t ...) s0) s11SELECT * FROM t0 JOIN t1 ON ... JOIN t2 ON ... (×500)SELECT * FROM t WHERE ((col_0 = 0 AND ...) OR ...) (depth=8, breadth=3)CREATE TABLE ...; INSERT INTO ...; SELECT ...; UPDATE ... (×50)WITH cte AS (SELECT CASE WHEN col_0 > 0 ... (×200)) SELECT * FROM cteINSERT scaling (Fix 3)
INSERT INTO t VALUES (0, 1), ... (4999, 5000)INSERT INTO t VALUES (0, 1), ... (9999, 10000)INSERT INTO t VALUES (0, 1), ... (24999, 25000)Testing