test_event_frequency.py 17 KB

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