From 4ec403ccbe32e965c24e93d8ec42d3ec83a2bd79 Mon Sep 17 00:00:00 2001 From: sundeep8967 Date: Thu, 27 Aug 2026 13:16:32 +0530 Subject: [PATCH] gh-156379: Avoid materializing large sequence ranges in mailbox.MH.get_sequences Intersect declared ranges directly with all_keys instead of enumerating the entire interval into a set. --- Lib/mailbox.py | 13 +++++++------ Lib/test/test_mailbox.py | 9 +++++++++ .../2026-08-27-08-00-00.gh-issue-156379.abcdef.rst | 1 + 3 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-08-27-08-00-00.gh-issue-156379.abcdef.rst diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 99426220154360..bad0776a267937 100644 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -1236,14 +1236,15 @@ def get_sequences(self): keys = set() for spec in contents.split(): if spec.isdigit(): - keys.add(int(spec)) + key = int(spec) + if key in all_keys: + keys.add(key) else: start, stop = (int(x) for x in spec.split('-')) - keys.update(range(start, stop + 1)) - results[name] = [key for key in sorted(keys) \ - if key in all_keys] - if len(results[name]) == 0: - del results[name] + if start <= stop: + keys.update(k for k in all_keys if start <= k <= stop) + if keys: + results[name] = sorted(keys) except ValueError: raise FormatError('Invalid sequence specification: %s' % line.rstrip()) diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 019c699bff55c4..488a443555af1d 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -1408,6 +1408,15 @@ def test_sequences(self): self._box.set_sequences({'foo':[key0]}) self.assertEqual(self._box.get_sequences(), {'foo':[key0]}) + def test_large_sequence_range(self): + # gh-156379: Verify large sequence ranges do not materialize large intervals + msg0 = mailbox.MHMessage(self._template % 0) + key0 = self._box.add(msg0) + seq_path = os.path.join(self._path, '.mh_sequences') + with open(seq_path, 'w', encoding='ASCII') as f: + f.write(f'unseen: 1-10000000\nempty: 50-100\n') + self.assertEqual(self._box.get_sequences(), {'unseen': [key0]}) + def test_no_dot_mh_sequences_file(self): path = os.path.join(self._path, 'foo.bar') os.mkdir(path) diff --git a/Misc/NEWS.d/next/Library/2026-08-27-08-00-00.gh-issue-156379.abcdef.rst b/Misc/NEWS.d/next/Library/2026-08-27-08-00-00.gh-issue-156379.abcdef.rst new file mode 100644 index 00000000000000..509ae1f52eb204 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-27-08-00-00.gh-issue-156379.abcdef.rst @@ -0,0 +1 @@ +Avoid materializing large sequence ranges in :meth:`mailbox.MH.get_sequences`.