test_event_frequency.py 17 KB

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