test_event_frequency.py 17 KB

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