Debian Codegraph @

tests/test_thread_safety.py

raw
1 import sys
2 import threading
3 import unittest
4 from concurrent.futures import ThreadPoolExecutor
5
6 import dateparser.data.date_translation_data.en as en_data
7 from dateparser.conf import settings as base_settings
8 from dateparser.date import DateDataParser
9 from dateparser.languages.dictionary import Dictionary
10 from dateparser.search import search_dates
11 from dateparser.search.search import DateSearchWithDetection, _ExactLanguageSearch
12 from tests import BaseTestCase
13
14
15 class TestThreadSafety(BaseTestCase):
16 """Regression tests for thread-safety issues.
17
18 See https://github.com/scrapinghub/dateparser/issues/441,
19 https://github.com/scrapinghub/dateparser/issues/1291 and
20 https://github.com/scrapinghub/dateparser/issues/1369.
21 """
22
23 def setUp(self):
24 super().setUp()
25 # A tiny thread-switch interval makes the interpreter yield between
26 # almost every bytecode, so the narrow check-then-read windows that
27 # cause the races below are exercised reliably instead of only once in
28 # a blue moon.
29 self._switch_interval = sys.getswitchinterval()
30 sys.setswitchinterval(1e-7)
31
32 def tearDown(self):
33 sys.setswitchinterval(self._switch_interval)
34 super().tearDown()
35
36 def _run_concurrently(self, func, args_list, workers=32):
37 with ThreadPoolExecutor(max_workers=workers) as executor:
38 futures = [executor.submit(func, arg) for arg in args_list]
39 return [future.result() for future in futures]
40
41 def test_dictionary_cache_eviction_concurrently(self):
42 # Issue #1291: concurrent population/eviction of the size-limited
43 # dictionary caches raised intermittent ``KeyError`` because the cache
44 # was read after a concurrent eviction could remove the entry.
45 dictionaries = [
46 Dictionary(
47 en_data.info,
48 base_settings.replace(CACHE_SIZE_LIMIT=1, SKIP_TOKENS=["tok%d" % i]),
49 )
50 for i in range(24)
51 ]
52
53 def hammer(index):
54 dictionary = dictionaries[index % len(dictionaries)]
55 for _ in range(50):
56 dictionary.split("2 days ago")
57 dictionary.are_tokens_valid(["2", "days", "ago"])
58 return True
59
60 results = self._run_concurrently(hammer, range(24))
61 self.assertTrue(all(results))
62
63 def test_settings_date_order_not_mutated_while_parsing(self):
64 # The absolute-time parser used to assign the locale-specific date order
65 # onto the shared Settings object in place (restoring it afterwards), so
66 # a concurrent parse could observe and use a foreign DATE_ORDER. Here the
67 # German locale order (DMY) differs from the configured default (MDY); a
68 # watcher thread asserts the shared setting never changes mid-parse.
69 parser = DateDataParser(
70 languages=["de"], settings={"PREFER_LOCALE_DATE_ORDER": True}
71 )
72 baseline = parser._settings.DATE_ORDER
73 self.assertEqual(baseline, "MDY")
74
75 observed = set()
76 stop = threading.Event()
77
78 def watch():
79 while not stop.is_set():
80 observed.add(parser._settings.DATE_ORDER)
81
82 def parse(i):
83 return parser.get_date_data(
84 ["02.03.2014", "2014-03-02", "11.12.2013"][i % 3]
85 )
86
87 watcher = threading.Thread(target=watch)
88 watcher.start()
89 try:
90 self._run_concurrently(parse, range(100), workers=16)
91 finally:
92 stop.set()
93 watcher.join()
94
95 self.assertEqual(observed, {baseline})
96
97 def test_search_does_not_mutate_shared_relative_base(self):
98 # search_dates used to assign RELATIVE_BASE onto the shared default
99 # Settings while resolving relative dates, polluting it for concurrent
100 # parses/searches.
101 text = (
102 "19 марта 2001. Сегодня был хороший день. "
103 "2 дня назад был хороший день. Вчера тоже был хороший день."
104 )
105 baseline = base_settings.RELATIVE_BASE
106
107 observed = set()
108 stop = threading.Event()
109
110 def watch():
111 while not stop.is_set():
112 observed.add(base_settings.RELATIVE_BASE)
113
114 def search(i):
115 return search_dates(text, languages=["ru"])
116
117 watcher = threading.Thread(target=watch)
118 watcher.start()
119 try:
120 results = self._run_concurrently(search, range(40), workers=8)
121 finally:
122 stop.set()
123 watcher.join()
124
125 self.assertTrue(all(result is not None for result in results))
126 self.assertEqual(observed, {baseline})
127
128 def test_detect_language_does_not_leave_narrowed_detector_on_instance(self):
129 # Issue #1369 site 1: detect_language used to stash a FullTextLanguageDetector
130 # on the process-wide singleton. _best_language narrows detector.languages
131 # in place, so a concurrent search_dates can load another call's already-
132 # narrowed detector and return None or a wrong date.
133 ds = DateSearchWithDetection()
134 detected = ds.detect_language("19 марта 2001", languages=["ru", "en"])
135 self.assertEqual(detected, "ru")
136 detector = getattr(ds, "language_detector", None)
137 if detector is not None:
138 leftover = [locale.shortname for locale in detector.languages]
139 self.assertEqual(
140 set(leftover),
141 {"ru", "en"},
142 "detect_language left a single-use detector narrowed in place "
143 "on the instance; concurrent search_dates can observe this "
144 "(issue #1369). leftover=%r" % leftover,
145 )
146
147 def test_concurrent_search_dates_does_not_share_language_detector(self):
148 # Issue #1369 site 1: the store/load gap is a few bytecodes, so park each
149 # thread immediately after it stores the detector. Sequential search_dates
150 # is not a valid RED for this race.
151 ru_text = "Договор подписан 19 марта 2001 года в Москве"
152 en_text = "The satellite was launched on 4 October 1957 from Baikonur"
153 sequential_ru = search_dates(ru_text, languages=["ru"])
154 sequential_en = search_dates(en_text, languages=["en"])
155 self.assertIsNotNone(sequential_ru)
156 self.assertIsNotNone(sequential_en)
157
158 slot = {}
159 barrier = threading.Barrier(2, timeout=10)
160
161 def _get(self):
162 return slot["v"]
163
164 def _set(self, value):
165 slot["v"] = value
166 try:
167 barrier.wait()
168 except threading.BrokenBarrierError:
169 pass
170
171 DateSearchWithDetection.language_detector = property(_get, _set)
172 try:
173 with ThreadPoolExecutor(max_workers=2) as executor:
174 ru, en = executor.map(
175 lambda args: search_dates(args[0], languages=[args[1]]),
176 [(ru_text, "ru"), (en_text, "en")],
177 )
178 finally:
179 del DateSearchWithDetection.language_detector
180
181 self.assertEqual(ru, sequential_ru)
182 self.assertEqual(en, sequential_en)
183
184 def test_concurrent_search_dates_does_not_share_locale_slot(self):
185 # Issue #1369 site 2: _ExactLanguageSearch.self.language is a 1-slot cache
186 # on the same singleton. Park after get_current_language so a store from
187 # the other thread lands before translate_search.
188 ru_text = "Договор подписан 19 марта 2001 года в Москве"
189 en_text = "The satellite was launched on 4 October 1957 from Baikonur"
190 sequential_ru = search_dates(ru_text, languages=["ru"])
191 sequential_en = search_dates(en_text, languages=["en"])
192 self.assertIsNotNone(sequential_ru)
193 self.assertIsNotNone(sequential_en)
194
195 original = _ExactLanguageSearch.get_current_language
196 barrier = threading.Barrier(2, timeout=10)
197
198 def patched(self, shortname):
199 result = original(self, shortname)
200 try:
201 barrier.wait()
202 except threading.BrokenBarrierError:
203 pass
204 return result
205
206 _ExactLanguageSearch.get_current_language = patched
207 try:
208 with ThreadPoolExecutor(max_workers=2) as executor:
209 ru, en = executor.map(
210 lambda args: search_dates(args[0], languages=[args[1]]),
211 [(ru_text, "ru"), (en_text, "en")],
212 )
213 finally:
214 _ExactLanguageSearch.get_current_language = original
215
216 self.assertEqual(ru, sequential_ru)
217 self.assertEqual(en, sequential_en)
218
219
220 if __name__ == "__main__":
221 unittest.main()