Skip to content

Commit 45e9b3d

Browse files
gh-162282: Fix quadratic cost in urllib.robotparser._add_entry (#162283)
* gh-162282: Fix quadratic cost in urllib.robotparser._add_entry Parsing a robots.txt with many identical User-agent: lines in a single group ran in O(N^2) time: _add_entry iterated entry.useragents without deduplication, and from the second duplicate on merge_entries was called once per iteration; merge_entries is itself O(N). Track the agents already registered during the current call and skip duplicates. For every input shape other than 'same agent repeated within one entry' the behavior is identical. On 10,000 duplicate User-agent lines the parse time drops from ~2.5 s to ~0.003 s. A regression test parses 50,000 duplicate User-agent lines and requires completion in under 5 seconds. * Update Lib/test/test_robotparser.py --------- Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
1 parent 434744e commit 45e9b3d

3 files changed

Lines changed: 20 additions & 0 deletions

File tree

‎Lib/test/test_robotparser.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,5 +875,20 @@ def test_read_404(self):
875875
self.assertIsNone(parser.crawl_delay('*'))
876876
self.assertIsNone(parser.request_rate('*'))
877877

878+
879+
class RepeatedUserAgentTest(unittest.TestCase):
880+
881+
def test_many_duplicate_user_agents(self):
882+
# gh-162282: a User-agent repeated within one group must not be
883+
# merged into that group once per repetition (quadratic time).
884+
body = "User-agent: evil\n" * 1000 + "Disallow: /\n"
885+
parser = urllib.robotparser.RobotFileParser()
886+
parser.parse(body.splitlines())
887+
entry = parser.groups["evil"]
888+
self.assertIs(entry, parser.entries[0])
889+
self.assertEqual(len(entry.rulelines), 1)
890+
self.assertFalse(parser.can_fetch("evil", "/"))
891+
892+
878893
if __name__=='__main__':
879894
unittest.main()

‎Lib/urllib/robotparser.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,12 @@ def read(self):
9090

9191
def _add_entry(self, entry):
9292
self.entries.append(entry)
93+
seen = set()
9394
for agent in entry.useragents:
9495
agent = agent.lower()
96+
if agent in seen:
97+
continue
98+
seen.add(agent)
9599
if agent not in self.groups:
96100
self.groups[agent] = entry
97101
else:
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix quadratic-time cost in :meth:`urllib.robotparser.RobotFileParser.parse` when a single group contains many identical ``User-agent:`` lines.

0 commit comments

Comments
 (0)