Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix variable lookup parse timing out with missing closing bracket #1684

Merged
merged 2 commits into from
Feb 2, 2023

Conversation

ggmichaelgo
Copy link
Contributor

@ggmichaelgo ggmichaelgo commented Feb 2, 2023

Problem

This PR #1680 has introduced a bug that causes VariableLookup#initialize to time out.
This happened when the VariableLookup's markup had a missing closing bracket and a very long string.

# this will execute within 50ms
"[12345678901234567890".scan /\[(?:[^\]\[]+|\g<0>)*\]/

# this will take a second to execute
"[123456789012345678901234".scan /\[(?:[^\]\[]+|\g<0>)*\]/

The regex is taking a long time to execute because the non-capturing group (?:[^\[^]+... recursively re-searches/backtraces the input with different lengths.
The non-capturing group match will look like this throughout the search:

  1. [123456789012345678901234
  2. [12345678901234567890123
  3. [1234567890123456789012
  4. [123456789012345678901
  5. [12345678901234567890
  6. and so on...

Solution

We can use the atomic group feature in regex to prevent regex from dividing the non-bracket characters, and early end the search.

\[(?:[^\[\]]+|\g<0>)*\]

\[          # match open bracket
(?>         # start an atomic capturing group (prevent backtracking)
  [^\[\]]+  # match non-square brackets
  |         # OR
  \g<0>     # go back to the beginning of the regex
)*          # end of non-capturing group
\]          # match closing bracket

@ggmichaelgo ggmichaelgo merged commit 4599e54 into master Feb 2, 2023
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.

2 participants