test_event_frequency.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. import time
  2. from copy import deepcopy
  3. from datetime import timedelta, timezone
  4. from unittest.mock import patch
  5. from uuid import uuid4
  6. import pytest
  7. from django.utils.timezone import now
  8. from sentry.issues.grouptype import PerformanceNPlusOneGroupType
  9. from sentry.models.rule import Rule
  10. from sentry.rules.conditions.event_frequency import (
  11. EventFrequencyCondition,
  12. EventFrequencyPercentCondition,
  13. EventUniqueUserFrequencyCondition,
  14. )
  15. from sentry.testutils.abstract import Abstract
  16. from sentry.testutils.cases import PerformanceIssueTestCase, RuleTestCase, SnubaTestCase
  17. from sentry.testutils.helpers.datetime import before_now, freeze_time, iso_format
  18. from sentry.testutils.silo import region_silo_test
  19. from sentry.testutils.skips import requires_snuba
  20. from sentry.utils.samples import load_data
  21. pytestmark = [requires_snuba]
  22. class ErrorEventMixin(SnubaTestCase):
  23. def add_event(self, data, project_id, timestamp):
  24. data["timestamp"] = iso_format(timestamp)
  25. # Store an error event
  26. event = self.store_event(
  27. data=data,
  28. project_id=project_id,
  29. )
  30. return event.for_group(event.group)
  31. class PerfIssuePlatformEventMixin(PerformanceIssueTestCase):
  32. def add_event(self, data, project_id, timestamp):
  33. fingerprint = data["fingerprint"][0]
  34. fingerprint = (
  35. fingerprint
  36. if "-" in fingerprint
  37. else f"{PerformanceNPlusOneGroupType.type_id}-{data['fingerprint'][0]}"
  38. )
  39. event_data = load_data(
  40. "transaction-n-plus-one",
  41. timestamp=timestamp.replace(tzinfo=timezone.utc),
  42. start_timestamp=timestamp.replace(tzinfo=timezone.utc),
  43. fingerprint=[fingerprint],
  44. )
  45. event_data["user"] = {"id": uuid4().hex}
  46. event_data["environment"] = data.get("environment")
  47. for tag in event_data["tags"]:
  48. if tag[0] == "environment":
  49. tag[1] = data.get("environment")
  50. break
  51. else:
  52. event_data["tags"].append(data.get("environment"))
  53. # Store a performance event
  54. event = self.create_performance_issue(
  55. event_data=event_data,
  56. project_id=project_id,
  57. fingerprint=fingerprint,
  58. )
  59. return event
  60. @pytest.mark.snuba_ci
  61. class StandardIntervalTestBase(SnubaTestCase, RuleTestCase):
  62. __test__ = Abstract(__module__, __qualname__)
  63. def add_event(self, data, project_id, timestamp):
  64. raise NotImplementedError
  65. def increment(self, event, count, environment=None, timestamp=None):
  66. raise NotImplementedError
  67. def _run_test(self, minutes, data, passes, add_events=False):
  68. if not self.environment:
  69. self.environment = self.create_environment(name="prod")
  70. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  71. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  72. event = self.add_event(
  73. data={
  74. "fingerprint": ["something_random"],
  75. "user": {"id": uuid4().hex},
  76. },
  77. project_id=self.project.id,
  78. timestamp=before_now(minutes=minutes),
  79. )
  80. if add_events:
  81. self.increment(
  82. event,
  83. data["value"] + 1,
  84. environment=self.environment.name,
  85. timestamp=now() - timedelta(minutes=minutes),
  86. )
  87. self.increment(
  88. event,
  89. data["value"] + 1,
  90. timestamp=now() - timedelta(minutes=minutes),
  91. )
  92. if passes:
  93. self.assertPasses(rule, event, is_new=False)
  94. self.assertPasses(environment_rule, event, is_new=False)
  95. else:
  96. self.assertDoesNotPass(rule, event, is_new=False)
  97. self.assertDoesNotPass(environment_rule, event, is_new=False)
  98. def test_one_minute_with_events(self):
  99. data = {"interval": "1m", "value": 6}
  100. self._run_test(data=data, minutes=1, passes=True, add_events=True)
  101. data = {"interval": "1m", "value": 16}
  102. self._run_test(data=data, minutes=1, passes=False)
  103. def test_one_hour_with_events(self):
  104. data = {"interval": "1h", "value": 6}
  105. self._run_test(data=data, minutes=60, passes=True, add_events=True)
  106. data = {"interval": "1h", "value": 16}
  107. self._run_test(data=data, minutes=60, passes=False)
  108. def test_one_day_with_events(self):
  109. data = {"interval": "1d", "value": 6}
  110. self._run_test(data=data, minutes=1440, passes=True, add_events=True)
  111. data = {"interval": "1d", "value": 16}
  112. self._run_test(data=data, minutes=1440, passes=False)
  113. def test_one_week_with_events(self):
  114. data = {"interval": "1w", "value": 6}
  115. self._run_test(data=data, minutes=10080, passes=True, add_events=True)
  116. data = {"interval": "1w", "value": 16}
  117. self._run_test(data=data, minutes=10080, passes=False)
  118. def test_one_minute_no_events(self):
  119. data = {"interval": "1m", "value": 6}
  120. self._run_test(data=data, minutes=1, passes=False)
  121. def test_one_hour_no_events(self):
  122. data = {"interval": "1h", "value": 6}
  123. self._run_test(data=data, minutes=60, passes=False)
  124. def test_one_day_no_events(self):
  125. data = {"interval": "1d", "value": 6}
  126. self._run_test(data=data, minutes=1440, passes=False)
  127. def test_one_week_no_events(self):
  128. data = {"interval": "1w", "value": 6}
  129. self._run_test(data=data, minutes=10080, passes=False)
  130. def test_comparison(self):
  131. # Test data is 4 events in the current period and 2 events in the comparison period, so
  132. # a 100% increase.
  133. event = self.add_event(
  134. data={
  135. "fingerprint": ["something_random"],
  136. "user": {"id": uuid4().hex},
  137. },
  138. project_id=self.project.id,
  139. timestamp=before_now(minutes=1),
  140. )
  141. self.increment(
  142. event,
  143. 3,
  144. timestamp=now() - timedelta(minutes=1),
  145. )
  146. self.increment(
  147. event,
  148. 2,
  149. timestamp=now() - timedelta(days=1, minutes=20),
  150. )
  151. data = {
  152. "interval": "1h",
  153. "value": 99,
  154. "comparisonType": "percent",
  155. "comparisonInterval": "1d",
  156. }
  157. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  158. self.assertPasses(rule, event, is_new=False)
  159. data = {
  160. "interval": "1h",
  161. "value": 101,
  162. "comparisonType": "percent",
  163. "comparisonInterval": "1d",
  164. }
  165. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  166. self.assertDoesNotPass(rule, event, is_new=False)
  167. def test_comparison_empty_comparison_period(self):
  168. # Test data is 1 event in the current period and 0 events in the comparison period. This
  169. # should always result in 0 and never fire.
  170. event = self.add_event(
  171. data={
  172. "fingerprint": ["something_random"],
  173. "user": {"id": uuid4().hex},
  174. },
  175. project_id=self.project.id,
  176. timestamp=before_now(minutes=1),
  177. )
  178. data = {
  179. "interval": "1h",
  180. "value": 0,
  181. "comparisonType": "percent",
  182. "comparisonInterval": "1d",
  183. }
  184. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  185. self.assertDoesNotPass(rule, event, is_new=False)
  186. data = {
  187. "interval": "1h",
  188. "value": 100,
  189. "comparisonType": "percent",
  190. "comparisonInterval": "1d",
  191. }
  192. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  193. self.assertDoesNotPass(rule, event, is_new=False)
  194. @patch("sentry.rules.conditions.event_frequency.BaseEventFrequencyCondition.get_rate")
  195. def test_is_new_issue_skips_snuba(self, mock_get_rate):
  196. # Looking for more than 1 event
  197. data = {"interval": "1m", "value": 6}
  198. minutes = 1
  199. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  200. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  201. event = self.add_event(
  202. data={
  203. "fingerprint": ["something_random"],
  204. "user": {"id": uuid4().hex},
  205. },
  206. project_id=self.project.id,
  207. timestamp=before_now(minutes=minutes),
  208. )
  209. # Issue is new and is the first event
  210. self.assertDoesNotPass(rule, event, is_new=True)
  211. self.assertDoesNotPass(environment_rule, event, is_new=True)
  212. assert mock_get_rate.call_count == 0
  213. class EventFrequencyConditionTestCase(StandardIntervalTestBase):
  214. __test__ = Abstract(__module__, __qualname__)
  215. rule_cls = EventFrequencyCondition
  216. def increment(self, event, count, environment=None, timestamp=None):
  217. timestamp = timestamp if timestamp else before_now(minutes=1)
  218. data = {"fingerprint": event.data["fingerprint"]}
  219. if environment:
  220. data["environment"] = environment
  221. for _ in range(count):
  222. self.add_event(
  223. data=data,
  224. project_id=self.project.id,
  225. timestamp=timestamp,
  226. )
  227. class EventUniqueUserFrequencyConditionTestCase(StandardIntervalTestBase):
  228. __test__ = Abstract(__module__, __qualname__)
  229. rule_cls = EventUniqueUserFrequencyCondition
  230. def increment(self, event, count, environment=None, timestamp=None):
  231. timestamp = timestamp if timestamp else before_now(minutes=1)
  232. data = {"fingerprint": event.data["fingerprint"]}
  233. if environment:
  234. data["environment"] = environment
  235. for _ in range(count):
  236. event_data = deepcopy(data)
  237. event_data["user"] = {"id": uuid4().hex}
  238. self.add_event(
  239. data=event_data,
  240. project_id=self.project.id,
  241. timestamp=timestamp,
  242. )
  243. class EventFrequencyPercentConditionTestCase(SnubaTestCase, RuleTestCase):
  244. __test__ = Abstract(__module__, __qualname__)
  245. rule_cls = EventFrequencyPercentCondition
  246. def add_event(self, data, project_id, timestamp):
  247. raise NotImplementedError
  248. def _make_sessions(self, num):
  249. received = time.time()
  250. def make_session(i):
  251. return dict(
  252. distinct_id=uuid4().hex,
  253. session_id=uuid4().hex,
  254. org_id=self.project.organization_id,
  255. project_id=self.project.id,
  256. status="ok",
  257. seq=0,
  258. release="foo@1.0.0",
  259. environment="prod",
  260. retention_days=90,
  261. duration=None,
  262. errors=0,
  263. # The line below is crucial to spread sessions throughout the time period.
  264. started=received - i,
  265. received=received,
  266. )
  267. self.bulk_store_sessions([make_session(i) for i in range(num)])
  268. def _run_test(self, minutes, data, passes, add_events=False):
  269. if not self.environment or self.environment.name != "prod":
  270. self.environment = self.create_environment(name="prod")
  271. if not hasattr(self, "test_event"):
  272. self.test_event = self.add_event(
  273. data={
  274. "fingerprint": ["something_random"],
  275. "user": {"id": uuid4().hex},
  276. "environment": self.environment.name,
  277. },
  278. project_id=self.project.id,
  279. timestamp=before_now(minutes=minutes),
  280. )
  281. if add_events:
  282. self.increment(
  283. self.test_event,
  284. max(1, int(minutes / 2)) - 1,
  285. environment=self.environment.name,
  286. timestamp=now() - timedelta(minutes=minutes),
  287. )
  288. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  289. environment_rule = self.get_rule(data=data, rule=Rule(environment_id=self.environment.id))
  290. if passes:
  291. self.assertPasses(rule, self.test_event, is_new=False)
  292. self.assertPasses(environment_rule, self.test_event, is_new=False)
  293. else:
  294. self.assertDoesNotPass(rule, self.test_event)
  295. self.assertDoesNotPass(environment_rule, self.test_event)
  296. def increment(self, event, count, environment=None, timestamp=None):
  297. data = {
  298. "fingerprint": event.data["fingerprint"],
  299. }
  300. timestamp = timestamp if timestamp else before_now(minutes=1)
  301. if environment:
  302. data["environment"] = environment
  303. for _ in range(count):
  304. event_data = deepcopy(data)
  305. event_data["user"] = {"id": uuid4().hex}
  306. self.add_event(
  307. data=event_data,
  308. project_id=self.project.id,
  309. timestamp=timestamp,
  310. )
  311. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  312. def test_five_minutes_with_events(self):
  313. self._make_sessions(60)
  314. data = {"interval": "5m", "value": 39}
  315. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  316. data = {"interval": "5m", "value": 41}
  317. self._run_test(data=data, minutes=5, passes=False)
  318. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  319. def test_ten_minutes_with_events(self):
  320. self._make_sessions(60)
  321. data = {"interval": "10m", "value": 49}
  322. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  323. data = {"interval": "10m", "value": 51}
  324. self._run_test(data=data, minutes=10, passes=False)
  325. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  326. def test_thirty_minutes_with_events(self):
  327. self._make_sessions(60)
  328. data = {"interval": "30m", "value": 49}
  329. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  330. data = {"interval": "30m", "value": 51}
  331. self._run_test(data=data, minutes=30, passes=False)
  332. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  333. def test_one_hour_with_events(self):
  334. self._make_sessions(60)
  335. data = {"interval": "1h", "value": 49}
  336. self._run_test(data=data, minutes=60, add_events=True, passes=True)
  337. data = {"interval": "1h", "value": 51}
  338. self._run_test(data=data, minutes=60, passes=False)
  339. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  340. def test_five_minutes_no_events(self):
  341. self._make_sessions(60)
  342. data = {"interval": "5m", "value": 39}
  343. self._run_test(data=data, minutes=5, passes=True, add_events=True)
  344. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  345. def test_ten_minutes_no_events(self):
  346. self._make_sessions(60)
  347. data = {"interval": "10m", "value": 49}
  348. self._run_test(data=data, minutes=10, passes=True, add_events=True)
  349. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  350. def test_thirty_minutes_no_events(self):
  351. self._make_sessions(60)
  352. data = {"interval": "30m", "value": 49}
  353. self._run_test(data=data, minutes=30, passes=True, add_events=True)
  354. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  355. def test_one_hour_no_events(self):
  356. self._make_sessions(60)
  357. data = {"interval": "1h", "value": 49}
  358. self._run_test(data=data, minutes=60, passes=False)
  359. @patch("sentry.rules.conditions.event_frequency.MIN_SESSIONS_TO_FIRE", 1)
  360. def test_comparison(self):
  361. self._make_sessions(10)
  362. # Create sessions for previous period
  363. self._make_sessions(10)
  364. # Test data is 2 events in the current period and 1 events in the comparison period.
  365. # Number of sessions is 20 in each period, so current period is 20% of sessions, prev
  366. # is 10%. Overall a 100% increase comparitively.
  367. event = self.add_event(
  368. data={"fingerprint": ["something_random"]},
  369. project_id=self.project.id,
  370. timestamp=before_now(minutes=1),
  371. )
  372. self.increment(
  373. event,
  374. 1,
  375. timestamp=now() - timedelta(minutes=1),
  376. )
  377. self.increment(
  378. event,
  379. 1,
  380. timestamp=now() - timedelta(days=1, minutes=20),
  381. )
  382. data = {
  383. "interval": "1h",
  384. "value": 99,
  385. "comparisonType": "percent",
  386. "comparisonInterval": "1d",
  387. }
  388. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  389. self.assertPasses(rule, event, is_new=False)
  390. data = {
  391. "interval": "1h",
  392. "value": 101,
  393. "comparisonType": "percent",
  394. "comparisonInterval": "1d",
  395. }
  396. rule = self.get_rule(data=data, rule=Rule(environment_id=None))
  397. self.assertDoesNotPass(rule, event, is_new=False)
  398. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  399. @region_silo_test
  400. class ErrorIssueFrequencyConditionTestCase(ErrorEventMixin, EventFrequencyConditionTestCase):
  401. pass
  402. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  403. @region_silo_test
  404. class PerfIssuePlatformIssueFrequencyConditionTestCase(
  405. PerfIssuePlatformEventMixin,
  406. EventFrequencyConditionTestCase,
  407. ):
  408. pass
  409. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  410. @region_silo_test
  411. class ErrorIssueUniqueUserFrequencyConditionTestCase(
  412. ErrorEventMixin,
  413. EventUniqueUserFrequencyConditionTestCase,
  414. ):
  415. pass
  416. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  417. @region_silo_test
  418. class PerfIssuePlatformIssueUniqueUserFrequencyConditionTestCase(
  419. PerfIssuePlatformEventMixin,
  420. EventUniqueUserFrequencyConditionTestCase,
  421. ):
  422. pass
  423. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  424. @region_silo_test
  425. class ErrorIssueEventFrequencyPercentConditionTestCase(
  426. ErrorEventMixin, EventFrequencyPercentConditionTestCase
  427. ):
  428. pass
  429. @freeze_time((now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0))
  430. @region_silo_test
  431. class PerfIssuePlatformIssueEventFrequencyPercentConditionTestCase(
  432. PerfIssuePlatformEventMixin,
  433. EventFrequencyPercentConditionTestCase,
  434. ):
  435. pass