← Back to Pull requests

ci: fail prechecks on regexes whose time grows superlinearly #22282

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Dec 02, 2026 09:33 UTC
Author

K9 innovation week project

Description

APPSEC-72086

Adds a Check regex linearity step to the prechecks job: scripts/lint regex-linearity runs scripts/check_regex_linearity.py (standard library only) when ddtrace/ or the script changes. It is also part of scripts/lint checks.

It fails only on a regex whose superlinear time it has measured in CPython:

1. Collect every re call in ddtrace/ and resolve its pattern and flags from the source (literals, concatenation, f-strings, %, .format, joins, re.escape, constants, loops and comprehensions over constant lists). Anything ambiguous (a name with conflicting bindings, an attribute, a list or generator something else could change or exhaust, a loop whose call does not run once per item, args/kwargs) is skipped and listed by --verbose, never guessed. vendor and _vendor directories are skipped.
2.
Time it the way the code calls it: match, fullmatch, a single search, or every match for sub, findall, finditer and split. A compiled regex is timed with the methods it is called with, followed only through an unambiguous binding (a use that could read another binding makes it unresolved); one stored where the check cannot follow it, such as a container or another object, is timed with finditer. A use that may not run as timed is also listed as unresolved: a match or fullmatch from a nonzero pos is not timed, while a search, findall or finditer from a nonzero pos, or a match or fullmatch method kept to be called later, is timed from position 0.
3.
Build attack inputs (about 800 per regex) from CPython's own parse tree of the pattern: repeated texts and delimiters, with endings that make the match fail.
4.
Screen them in a subprocess at 4 to 16 KB, using CPU time: a candidate's time must grow at least 2.5x per doubling, twice.
5.
Confirm each candidate with a growth curve in fresh subprocesses, timed again since noise only adds time: at least three points up to a quarter of a second with a fitted exponent of at least 1.5 and every step superlinear, or exponential growth, or a timeout seen twice.

Example report (from the ddtrace/ tree before #22194):

ddtrace/llmobs/_evaluators/llm_judge.py:879: polynomial (time grows as n**2.0), with every match of re.finditer, as sub, findall and split do
    pattern: '\\{\\{(.+?)\\}\\}'
    input:   '' + '{' * n + ''
    timings: 512 chars 0.001 s, ..., 11,556 chars 0.299 s (CPU time)
    repro:   python3 -c 'import re, time; ...'

CodeQL is not used: it isn't in the testrunner image, and it skips patterns with a backreference or built by concatenation, both of which hid superlinear regexes here.

Customer impact

None: CI and lint tooling only.

Testing

  • tests/internal/test_check_regex_linearity.py (44 tests) covers resolution and unresolved calls, method selection, attack generation, the verdict rules (repeated timing, early stop, timeouts, crashes), the report and the exit code. It passes on Python 3.9 and 3.14, and in a testrunner container limited to 2 CPUs.

  • On ddtrace/ the check resolves 134 regexes, lists 18 calls as unresolved (4 of them still timed) and reports none (at 98411c2456). On the tree before the APPSEC-72086 fixes (498511e8e1) it reports the 18 regexes fixed under that ticket, and on a synthetic corpus every exponential, quadratic and cubic case and no linear one.

  • The findings were the same on a 16-core laptop with every core busy, in the 2-CPU container with competing processes, and on a reviewer's 5-CPU sandbox under heavy load.
  • Risks

  • Every regex in ddtrace/ must be linear for the precheck to pass. The regexes it found were fixed first, in #22183, #22192, #22194, #22200, #22215, #22216, #22226, #22283 and #22292.

  • No allowlist or inline suppression, by choice. A finding is a regex to fix, so the check never guesses a pattern or flags. Where it cannot follow a call it times a costly case instead (finditer, the costliest method but fullmatch, for a compiled regex; no limit for an unresolved count, maxsplit or endpos; position 0 for a search from a later pos) and it does not see changes made by other modules, so it can report a regex the code runs faster; that would be fixed in the check itself.

  • It never fails on its own errors. An error of the check skips the file, call or regex it happened on and is printed; only a measured superlinear regex fails the check. To bound memory and time, a value over 16,384 characters, a module whose resolved values exceed a million, a pattern over 4,096 characters, and a call that needs over 100,000 evaluations and visited items are left unresolved, and a regex whose pattern names over 256 distinct characters, or that would get over 20,000 attack inputs, is not timed. A run that reaches 480 s kills its timing children, reports the findings measured so far, lists what it did not check, and fails only on those findings; each timing child also ends itself a minute after that limit.

  • Misses. Skipped calls (listed by --verbose), inputs the heuristic attack generation never builds, and calls with a constant endpos of at most 16 are not checked. A compiled regex the check cannot follow (stored in a container or on another object, or only used from another module) is timed with finditer only, so one that is slow only with fullmatch passes. A call listed but still timed (a later pos, a method kept for later) can also be slower at run time than as timed.

  • Time.* A scan of ddtrace/ takes 4 to 9 s on a laptop and was measured at 36 to 39 s on a 5-CPU sandbox (180 s under heavy load). Confirming a real finding costs seconds, up to about a minute under load.
  • Additional Notes

    Run it locally with scripts/lint regex-linearity [paths...] [--verbose].

    🤖 Generated with Claude Code

    [APPSEC-72086]: https://datadoghq.atlassian.net/browse/APPSEC-72086?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: christophe-papazian Review duration: 4716m
    All Vouch review confidence checks passed
    Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    46%
    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.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #22282"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 46.7% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 46.7% · Lower = rushed or shallow review
    46.7%
    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: 27.7% · Safe to merge
    27.7%