test_event_frequency.py 17 KB

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