Skip to content

Commit 78dec8d

Browse files
miss-islingtonVadimToptunovasvetlov
authored
[3.14] gh-162282: Fix quadratic cost in urllib.robotparser._add_entry (GH-162283) (#162447)
gh-162282: Fix quadratic cost in urllib.robotparser._add_entry (GH-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 --------- (cherry picked from commit 45e9b3d) Co-authored-by: Vadim Toptunov <vtoptunov88@gmail.com> Co-authored-by: Andrew Svetlov <andrew.svetlov@gmail.com>
1 parent 425fe26 commit 78dec8d

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
@@ -844,5 +844,20 @@ def test_read_404(self):
844844
self.assertIsNone(parser.crawl_delay('*'))
845845
self.assertIsNone(parser.request_rate('*'))
846846

847+
848+
class RepeatedUserAgentTest(unittest.TestCase):
849+
850+
def test_many_duplicate_user_agents(self):
851+
# gh-162282: a User-agent repeated within one group must not be
852+
# merged into that group once per repetition (quadratic time).
853+
body = "User-agent: evil\n" * 1000 + "Disallow: /\n"
854+
parser = urllib.robotparser.RobotFileParser()
855+
parser.parse(body.splitlines())
856+
entry = parser.groups["evil"]
857+
self.assertIs(entry, parser.entries[0])
858+
self.assertEqual(len(entry.rulelines), 1)
859+
self.assertFalse(parser.can_fetch("evil", "/"))
860+
861+
847862
if __name__=='__main__':
848863
unittest.main()

‎Lib/urllib/robotparser.py‎

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

8484
def _add_entry(self, entry):
8585
self.entries.append(entry)
86+
seen = set()
8687
for agent in entry.useragents:
8788
agent = agent.lower()
89+
if agent in seen:
90+
continue
91+
seen.add(agent)
8892
if agent not in self.groups:
8993
self.groups[agent] = entry
9094
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)