Skip to content

perf: fix O(n²) catastrophic backtracking in redact regex#4779

Closed
acsezen wants to merge 1 commit intoNousResearch:mainfrom
acsezen:fix/redact-regex-catastrophic-backtracking
Closed

perf: fix O(n²) catastrophic backtracking in redact regex#4779
acsezen wants to merge 1 commit intoNousResearch:mainfrom
acsezen:fix/redact-regex-catastrophic-backtracking

Conversation

@acsezen
Copy link
Copy Markdown
Contributor

@acsezen acsezen commented Apr 3, 2026

Problem

Three tests in test_file_read_guards.py consistently time out on CI (30s limit):

  • TestCharacterCountGuard::test_content_under_limit_passes
  • TestCharacterCountGuard::test_oversized_read_rejected
  • TestConfigOverride::test_custom_config_raises_limit

These are pre-existing issues unrelated to any feature PR.

Root Cause

1. O(n²) regex in agent/redact.py

_ENV_ASSIGN_RE uses unbounded [A-Z_]* with IGNORECASE, which matches any letter or underscore. On 100K+ character uniform strings (like the test fixtures), the engine tries every start position, greedily matches to end-of-string, then backtracks character-by-character looking for API_KEY/TOKEN/etc. This is classic catastrophic backtracking.

Empirical timing: 5K chars → 0.2s, 10K → 0.6s, 20K → 2.4s, 100K → ~60s (extrapolated).

2. Guard ordering in tools/file_tools.py

redact_sensitive_text() ran BEFORE the character-count guard, so oversized content (that would be rejected anyway) went through the expensive regex first.

Fix

  1. agent/redact.py: Bound [A-Z_]* to [A-Z_]{0,50} — env var names are never 50K+ chars. Same matching for real-world input, eliminates pathological backtracking.

  2. tools/file_tools.py: Move character-count guard before redaction. Content exceeding the limit is rejected immediately without touching the regex. Redaction only runs on content that passes the size check.

Result

All 19 tests in test_file_read_guards.py pass in 2.6s (previously 3 timed out at 30s+).

…ile read guard

Two pre-existing issues causing test_file_read_guards timeouts on CI:

1. agent/redact.py: _ENV_ASSIGN_RE used unbounded [A-Z_]* with
   IGNORECASE, matching any letter/underscore to end-of-string at
   each position → O(n²) backtracking on 100K+ char inputs.
   Bounded to {0,50} since env var names are never that long.

2. tools/file_tools.py: redact_sensitive_text() ran BEFORE the
   character-count guard, so oversized content (that would be rejected
   anyway) went through the expensive regex first. Reordered to check
   size limit before redaction.
@teknium1
Copy link
Copy Markdown
Contributor

teknium1 commented Apr 4, 2026

Merged via PR #4962. Cherry-picked onto current main with authorship preserved. Clean fix — 81 tests now pass in 0.20s instead of timing out. Thanks!

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