test_event_frequency.py 18 KB

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