Skip to content

gh-163137: Fix quadratic time in fnmatch.translate() for unclosed '[' - #163138

Open
kksecure wants to merge 1 commit into
python:mainfrom
kksecure:gh-163137-fnmatch-quadratic
Open

kksecure wants to merge 1 commit into
python:mainfrom
kksecure:gh-163137-fnmatch-quadratic

Conversation

@kksecure

@kksecure kksecure commented Dec 4, 2026

Copy link
Copy Markdown

Each [ in a pattern scans to the end of the pattern looking for the closing ]. If there is none, the [ becomes a literal and the next [ scans again, so a pattern of many unclosed brackets ("[!" * n) takes O(n²) time in fnmatch.translate() and everything built on it (fnmatch, fnmatchcase, filter, glob.translate(), pathlib.PurePath.full_match()).

If there is no ] after the current position, the scan can't succeed, and neither can the scan for any later [. This change finds the last ] once and skips the scan when we're past it. The output is unchanged:

  • The existing test_fnmatch, test_glob and test_pathlib pass (1,449 tests).
  • translate() gives identical output before and after on 300,000 random patterns over []!-^*?ab\.
  • New test test_translate_unclosed_brackets: about 0.8 s with the fix. Without it, the same test takes 8 min 14 s on a debug build.

Timings for "[!" * n on a release build (3.15.2): 32 KB went from 9.7 s to under 0.01 s, and 200 KB now takes 0.03 s.

…ed '['

Each '[' scanned to the end of the pattern looking for ']'.  When there
is no ']' after the current position, that scan always fails, and so does
the scan for every later '['.  Find the last ']' once and treat any '['
after it as a literal without scanning.
@python-cla-bot

python-cla-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Comment thread Lib/fnmatch.py
star_indices = []

i, n = 0, len(pat)
last_close = pat.rfind(']')

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.

This adds some overhead to the cases where no [ or ']` is involved. Can you benchmark some relevant cases?

Comment thread Lib/fnmatch.py
Comment on lines 124 to 126
while j < n and pat[j] != ']':
j = j+1
if j >= n:

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.

This part is still a linear search. We could do something like

Suggested change
j = pat.find(']', j) if may_close else -1
if j < 0:
# No ']' left: every later '[' is a literal too.
may_close = False

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants