test_event_frequency.py 17 KB

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