test_tsdb_backend.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. from datetime import datetime, timedelta
  2. from unittest.mock import patch
  3. import pytz
  4. from sentry.models import Environment, Group, GroupRelease, Release
  5. from sentry.testutils import SnubaTestCase, TestCase
  6. from sentry.testutils.helpers.datetime import iso_format
  7. from sentry.testutils.perfomance_issues.store_transaction import PerfIssueTransactionTestMixin
  8. from sentry.testutils.silo import region_silo_test
  9. from sentry.tsdb.base import TSDBModel
  10. from sentry.tsdb.snuba import SnubaTSDB
  11. from sentry.types.issues import GroupType
  12. from sentry.utils.dates import to_datetime, to_timestamp
  13. from sentry.utils.snuba import aliased_query
  14. def timestamp(d):
  15. t = int(to_timestamp(d))
  16. return t - (t % 3600)
  17. def has_shape(data, shape, allow_empty=False):
  18. """
  19. Determine if a data object has the provided shape
  20. At any level, the object in `data` and in `shape` must have the same type.
  21. A dict is the same shape if all its keys and values have the same shape as the
  22. key/value in `shape`. The number of keys/values is not relevant.
  23. A list is the same shape if all its items have the same shape as the value
  24. in `shape`
  25. A tuple is the same shape if it has the same length as `shape` and all the
  26. values have the same shape as the corresponding value in `shape`
  27. Any other object simply has to have the same type.
  28. If `allow_empty` is set, lists and dicts in `data` will pass even if they are empty.
  29. """
  30. if not isinstance(data, type(shape)):
  31. return False
  32. if isinstance(data, dict):
  33. return (
  34. (allow_empty or len(data) > 0)
  35. and all(has_shape(k, list(shape.keys())[0]) for k in data.keys())
  36. and all(has_shape(v, list(shape.values())[0]) for v in data.values())
  37. )
  38. elif isinstance(data, list):
  39. return (allow_empty or len(data) > 0) and all(has_shape(v, shape[0]) for v in data)
  40. elif isinstance(data, tuple):
  41. return len(data) == len(shape) and all(
  42. has_shape(data[i], shape[i]) for i in range(len(data))
  43. )
  44. else:
  45. return True
  46. class SnubaTSDBTest(TestCase, SnubaTestCase):
  47. def setUp(self):
  48. super().setUp()
  49. self.db = SnubaTSDB()
  50. self.now = (datetime.utcnow() - timedelta(hours=4)).replace(
  51. hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC
  52. )
  53. self.proj1 = self.create_project()
  54. env1 = "test"
  55. env2 = "dev"
  56. defaultenv = ""
  57. release1 = "1" * 10
  58. release2 = "2" * 10
  59. self.release1 = Release.objects.create(
  60. organization_id=self.organization.id, version=release1, date_added=self.now
  61. )
  62. self.release1.add_project(self.proj1)
  63. self.release2 = Release.objects.create(
  64. organization_id=self.organization.id, version=release2, date_added=self.now
  65. )
  66. self.release2.add_project(self.proj1)
  67. for r in range(0, 14400, 600): # Every 10 min for 4 hours
  68. self.store_event(
  69. data={
  70. "event_id": (str(r) * 32)[:32],
  71. "message": "message 1",
  72. "platform": "python",
  73. "fingerprint": [["group-1"], ["group-2"]][
  74. (r // 600) % 2
  75. ], # Switch every 10 mins
  76. "timestamp": iso_format(self.now + timedelta(seconds=r)),
  77. "tags": {
  78. "foo": "bar",
  79. "baz": "quux",
  80. # Switch every 2 hours
  81. "environment": [env1, None][(r // 7200) % 3],
  82. "sentry:user": f"id:user{r // 3300}",
  83. },
  84. "user": {
  85. # change every 55 min so some hours have 1 user, some have 2
  86. "id": f"user{r // 3300}",
  87. },
  88. "release": str(r // 3600) * 10, # 1 per hour,
  89. },
  90. project_id=self.proj1.id,
  91. )
  92. groups = Group.objects.filter(project=self.proj1).order_by("id")
  93. self.proj1group1 = groups[0]
  94. self.proj1group2 = groups[1]
  95. self.env1 = Environment.objects.get(name=env1)
  96. self.env2 = self.create_environment(name=env2) # No events
  97. self.defaultenv = Environment.objects.get(name=defaultenv)
  98. self.group1release1env1 = GroupRelease.objects.get(
  99. project_id=self.proj1.id,
  100. group_id=self.proj1group1.id,
  101. release_id=self.release1.id,
  102. environment=env1,
  103. )
  104. self.group1release2env1 = GroupRelease.objects.create(
  105. project_id=self.proj1.id,
  106. group_id=self.proj1group1.id,
  107. release_id=self.release2.id,
  108. environment=env1,
  109. )
  110. self.group2release1env1 = GroupRelease.objects.get(
  111. project_id=self.proj1.id,
  112. group_id=self.proj1group2.id,
  113. release_id=self.release1.id,
  114. environment=env1,
  115. )
  116. def test_range_single(self):
  117. env1 = "test"
  118. project = self.create_project()
  119. for r in range(0, 600 * 6 * 4, 300): # Every 10 min for 4 hours
  120. self.store_event(
  121. data={
  122. "event_id": (str(r) * 32)[:32],
  123. "message": "message 1",
  124. "platform": "python",
  125. "fingerprint": ["group-1"],
  126. "timestamp": iso_format(self.now + timedelta(seconds=r)),
  127. "tags": {
  128. "foo": "bar",
  129. "baz": "quux",
  130. # Switch every 2 hours
  131. "environment": [env1, None][(r // 7200) % 3],
  132. "sentry:user": f"id:user{r // 3300}",
  133. },
  134. "user": {
  135. # change every 55 min so some hours have 1 user, some have 2
  136. "id": f"user{r // 3300}",
  137. },
  138. "release": str(r // 3600) * 10, # 1 per hour,
  139. },
  140. project_id=project.id,
  141. )
  142. groups = Group.objects.filter(project=project).order_by("id")
  143. group = groups[0]
  144. dts = [self.now + timedelta(hours=i) for i in range(4)]
  145. assert self.db.get_range(TSDBModel.group, [group.id], dts[0], dts[-1], rollup=3600) == {
  146. group.id: [
  147. (timestamp(dts[0]), 6 * 2),
  148. (timestamp(dts[1]), 6 * 2),
  149. (timestamp(dts[2]), 6 * 2),
  150. (timestamp(dts[3]), 6 * 2),
  151. ]
  152. }
  153. def test_range_groups(self):
  154. dts = [self.now + timedelta(hours=i) for i in range(4)]
  155. assert self.db.get_range(
  156. TSDBModel.group, [self.proj1group1.id], dts[0], dts[-1], rollup=3600
  157. ) == {
  158. self.proj1group1.id: [
  159. (timestamp(dts[0]), 3),
  160. (timestamp(dts[1]), 3),
  161. (timestamp(dts[2]), 3),
  162. (timestamp(dts[3]), 3),
  163. ]
  164. }
  165. # Multiple groups
  166. assert self.db.get_range(
  167. TSDBModel.group,
  168. [self.proj1group1.id, self.proj1group2.id],
  169. dts[0],
  170. dts[-1],
  171. rollup=3600,
  172. ) == {
  173. self.proj1group1.id: [
  174. (timestamp(dts[0]), 3),
  175. (timestamp(dts[1]), 3),
  176. (timestamp(dts[2]), 3),
  177. (timestamp(dts[3]), 3),
  178. ],
  179. self.proj1group2.id: [
  180. (timestamp(dts[0]), 3),
  181. (timestamp(dts[1]), 3),
  182. (timestamp(dts[2]), 3),
  183. (timestamp(dts[3]), 3),
  184. ],
  185. }
  186. assert self.db.get_range(TSDBModel.group, [], dts[0], dts[-1], rollup=3600) == {}
  187. def test_range_releases(self):
  188. dts = [self.now + timedelta(hours=i) for i in range(4)]
  189. assert self.db.get_range(
  190. TSDBModel.release, [self.release1.id], dts[0], dts[-1], rollup=3600
  191. ) == {
  192. self.release1.id: [
  193. (timestamp(dts[0]), 0),
  194. (timestamp(dts[1]), 6),
  195. (timestamp(dts[2]), 0),
  196. (timestamp(dts[3]), 0),
  197. ]
  198. }
  199. def test_range_project(self):
  200. dts = [self.now + timedelta(hours=i) for i in range(4)]
  201. assert self.db.get_range(
  202. TSDBModel.project, [self.proj1.id], dts[0], dts[-1], rollup=3600
  203. ) == {
  204. self.proj1.id: [
  205. (timestamp(dts[0]), 6),
  206. (timestamp(dts[1]), 6),
  207. (timestamp(dts[2]), 6),
  208. (timestamp(dts[3]), 6),
  209. ]
  210. }
  211. def test_range_environment_filter(self):
  212. dts = [self.now + timedelta(hours=i) for i in range(4)]
  213. assert self.db.get_range(
  214. TSDBModel.project,
  215. [self.proj1.id],
  216. dts[0],
  217. dts[-1],
  218. rollup=3600,
  219. environment_ids=[self.env1.id],
  220. ) == {
  221. self.proj1.id: [
  222. (timestamp(dts[0]), 6),
  223. (timestamp(dts[1]), 6),
  224. (timestamp(dts[2]), 0),
  225. (timestamp(dts[3]), 0),
  226. ]
  227. }
  228. # No events submitted for env2
  229. assert self.db.get_range(
  230. TSDBModel.project,
  231. [self.proj1.id],
  232. dts[0],
  233. dts[-1],
  234. rollup=3600,
  235. environment_ids=[self.env2.id],
  236. ) == {
  237. self.proj1.id: [
  238. (timestamp(dts[0]), 0),
  239. (timestamp(dts[1]), 0),
  240. (timestamp(dts[2]), 0),
  241. (timestamp(dts[3]), 0),
  242. ]
  243. }
  244. # Events submitted with no environment should match default environment
  245. assert self.db.get_range(
  246. TSDBModel.project,
  247. [self.proj1.id],
  248. dts[0],
  249. dts[-1],
  250. rollup=3600,
  251. environment_ids=[self.defaultenv.id],
  252. ) == {
  253. self.proj1.id: [
  254. (timestamp(dts[0]), 0),
  255. (timestamp(dts[1]), 0),
  256. (timestamp(dts[2]), 6),
  257. (timestamp(dts[3]), 6),
  258. ]
  259. }
  260. def test_range_rollups(self):
  261. # Daily
  262. daystart = self.now.replace(hour=0) # day buckets start on day boundaries
  263. dts = [daystart + timedelta(days=i) for i in range(2)]
  264. assert self.db.get_range(
  265. TSDBModel.project, [self.proj1.id], dts[0], dts[-1], rollup=86400
  266. ) == {self.proj1.id: [(timestamp(dts[0]), 24), (timestamp(dts[1]), 0)]}
  267. # Minutely
  268. dts = [self.now + timedelta(minutes=i) for i in range(120)]
  269. # Expect every 10th minute to have a 1, else 0
  270. expected = [(to_timestamp(d), 1 if i % 10 == 0 else 0) for i, d in enumerate(dts)]
  271. assert self.db.get_range(
  272. TSDBModel.project, [self.proj1.id], dts[0], dts[-1], rollup=60
  273. ) == {self.proj1.id: expected}
  274. def test_distinct_counts_series_users(self):
  275. dts = [self.now + timedelta(hours=i) for i in range(4)]
  276. assert self.db.get_distinct_counts_series(
  277. TSDBModel.users_affected_by_group, [self.proj1group1.id], dts[0], dts[-1], rollup=3600
  278. ) == {
  279. self.proj1group1.id: [
  280. (timestamp(dts[0]), 1),
  281. (timestamp(dts[1]), 1),
  282. (timestamp(dts[2]), 1),
  283. (timestamp(dts[3]), 2),
  284. ]
  285. }
  286. dts = [self.now + timedelta(hours=i) for i in range(4)]
  287. assert self.db.get_distinct_counts_series(
  288. TSDBModel.users_affected_by_project, [self.proj1.id], dts[0], dts[-1], rollup=3600
  289. ) == {
  290. self.proj1.id: [
  291. (timestamp(dts[0]), 1),
  292. (timestamp(dts[1]), 2),
  293. (timestamp(dts[2]), 2),
  294. (timestamp(dts[3]), 2),
  295. ]
  296. }
  297. assert (
  298. self.db.get_distinct_counts_series(
  299. TSDBModel.users_affected_by_group, [], dts[0], dts[-1], rollup=3600
  300. )
  301. == {}
  302. )
  303. def get_distinct_counts_totals_users(self):
  304. assert self.db.get_distinct_counts_totals(
  305. TSDBModel.users_affected_by_group,
  306. [self.proj1group1.id],
  307. self.now,
  308. self.now + timedelta(hours=4),
  309. rollup=3600,
  310. ) == {
  311. self.proj1group1.id: 2 # 2 unique users overall
  312. }
  313. assert self.db.get_distinct_counts_totals(
  314. TSDBModel.users_affected_by_group,
  315. [self.proj1group1.id],
  316. self.now,
  317. self.now,
  318. rollup=3600,
  319. ) == {
  320. self.proj1group1.id: 1 # Only 1 unique user in the first hour
  321. }
  322. assert self.db.get_distinct_counts_totals(
  323. TSDBModel.users_affected_by_project,
  324. [self.proj1.id],
  325. self.now,
  326. self.now + timedelta(hours=4),
  327. rollup=3600,
  328. ) == {self.proj1.id: 2}
  329. assert (
  330. self.db.get_distinct_counts_totals(
  331. TSDBModel.users_affected_by_group,
  332. [],
  333. self.now,
  334. self.now + timedelta(hours=4),
  335. rollup=3600,
  336. )
  337. == {}
  338. )
  339. def test_most_frequent(self):
  340. assert self.db.get_most_frequent(
  341. TSDBModel.frequent_issues_by_project,
  342. [self.proj1.id],
  343. self.now,
  344. self.now + timedelta(hours=4),
  345. rollup=3600,
  346. ) in [
  347. {self.proj1.id: [(self.proj1group1.id, 2.0), (self.proj1group2.id, 1.0)]},
  348. {self.proj1.id: [(self.proj1group2.id, 2.0), (self.proj1group1.id, 1.0)]},
  349. ] # Both issues equally frequent
  350. assert (
  351. self.db.get_most_frequent(
  352. TSDBModel.frequent_issues_by_project,
  353. [],
  354. self.now,
  355. self.now + timedelta(hours=4),
  356. rollup=3600,
  357. )
  358. == {}
  359. )
  360. def test_frequency_series(self):
  361. dts = [self.now + timedelta(hours=i) for i in range(4)]
  362. assert self.db.get_frequency_series(
  363. TSDBModel.frequent_releases_by_group,
  364. {
  365. self.proj1group1.id: (self.group1release1env1.id, self.group1release2env1.id),
  366. self.proj1group2.id: (self.group2release1env1.id,),
  367. },
  368. dts[0],
  369. dts[-1],
  370. rollup=3600,
  371. ) == {
  372. self.proj1group1.id: [
  373. (timestamp(dts[0]), {self.group1release1env1.id: 0, self.group1release2env1.id: 0}),
  374. (timestamp(dts[1]), {self.group1release1env1.id: 3, self.group1release2env1.id: 0}),
  375. (timestamp(dts[2]), {self.group1release1env1.id: 0, self.group1release2env1.id: 3}),
  376. (timestamp(dts[3]), {self.group1release1env1.id: 0, self.group1release2env1.id: 0}),
  377. ],
  378. self.proj1group2.id: [
  379. (timestamp(dts[0]), {self.group2release1env1.id: 0}),
  380. (timestamp(dts[1]), {self.group2release1env1.id: 3}),
  381. (timestamp(dts[2]), {self.group2release1env1.id: 0}),
  382. (timestamp(dts[3]), {self.group2release1env1.id: 0}),
  383. ],
  384. }
  385. assert (
  386. self.db.get_frequency_series(
  387. TSDBModel.frequent_releases_by_group, {}, dts[0], dts[-1], rollup=3600
  388. )
  389. == {}
  390. )
  391. def test_result_shape(self):
  392. """
  393. Tests that the results from the different TSDB methods have the
  394. expected format.
  395. """
  396. project_id = self.proj1.id
  397. dts = [self.now + timedelta(hours=i) for i in range(4)]
  398. results = self.db.get_most_frequent(
  399. TSDBModel.frequent_issues_by_project, [project_id], dts[0], dts[0]
  400. )
  401. assert has_shape(results, {1: [(1, 1.0)]})
  402. results = self.db.get_most_frequent_series(
  403. TSDBModel.frequent_issues_by_project, [project_id], dts[0], dts[0]
  404. )
  405. assert has_shape(results, {1: [(1, {1: 1.0})]})
  406. items = {
  407. # {project_id: (issue_id, issue_id, ...)}
  408. project_id: (self.proj1group1.id, self.proj1group2.id)
  409. }
  410. results = self.db.get_frequency_series(
  411. TSDBModel.frequent_issues_by_project, items, dts[0], dts[-1]
  412. )
  413. assert has_shape(results, {1: [(1, {1: 1})]})
  414. results = self.db.get_frequency_totals(
  415. TSDBModel.frequent_issues_by_project, items, dts[0], dts[-1]
  416. )
  417. assert has_shape(results, {1: {1: 1}})
  418. results = self.db.get_range(TSDBModel.project, [project_id], dts[0], dts[-1])
  419. assert has_shape(results, {1: [(1, 1)]})
  420. results = self.db.get_distinct_counts_series(
  421. TSDBModel.users_affected_by_project, [project_id], dts[0], dts[-1]
  422. )
  423. assert has_shape(results, {1: [(1, 1)]})
  424. results = self.db.get_distinct_counts_totals(
  425. TSDBModel.users_affected_by_project, [project_id], dts[0], dts[-1]
  426. )
  427. assert has_shape(results, {1: 1})
  428. results = self.db.get_distinct_counts_union(
  429. TSDBModel.users_affected_by_project, [project_id], dts[0], dts[-1]
  430. )
  431. assert has_shape(results, 1)
  432. def test_calculated_limit(self):
  433. with patch("sentry.tsdb.snuba.snuba") as snuba:
  434. # 24h test
  435. rollup = 3600
  436. end = self.now
  437. start = end + timedelta(days=-1, seconds=rollup)
  438. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  439. assert snuba.query.call_args[1]["limit"] == 120
  440. # 14 day test
  441. rollup = 86400
  442. start = end + timedelta(days=-14, seconds=rollup)
  443. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  444. assert snuba.query.call_args[1]["limit"] == 70
  445. # 1h test
  446. rollup = 3600
  447. end = self.now
  448. start = end + timedelta(hours=-1, seconds=rollup)
  449. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  450. assert snuba.query.call_args[1]["limit"] == 5
  451. @region_silo_test
  452. class SnubaTSDBGroupPerformanceTest(TestCase, SnubaTestCase, PerfIssueTransactionTestMixin):
  453. def setUp(self):
  454. super().setUp()
  455. self.db = SnubaTSDB()
  456. self.now = (datetime.utcnow() - timedelta(hours=4)).replace(
  457. hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC
  458. )
  459. self.proj1 = self.create_project()
  460. self.env1 = Environment.objects.get_or_create(
  461. organization_id=self.proj1.organization_id, name="test"
  462. )[0]
  463. self.env2 = Environment.objects.get_or_create(
  464. organization_id=self.proj1.organization_id, name="dev"
  465. )[0]
  466. defaultenv = ""
  467. group1_fingerprint = f"{GroupType.PERFORMANCE_SLOW_SPAN.value}-group1"
  468. group2_fingerprint = f"{GroupType.PERFORMANCE_N_PLUS_ONE.value}-group2"
  469. for r in range(0, 14400, 600): # Every 10 min for 4 hours
  470. event = self.store_transaction(
  471. environment=[self.env1, None][(r // 7200) % 3],
  472. project_id=self.proj1.id,
  473. # change every 55 min so some hours have 1 user, some have 2
  474. user_id=f"user{r // 3300}",
  475. # release_version=str(r // 3600) * 10, # 1 per hour,
  476. timestamp=self.now + timedelta(seconds=r),
  477. fingerprint=[group1_fingerprint, group2_fingerprint] if ((r // 600) % 2) else [],
  478. )
  479. self.proj1group1 = event.groups[0]
  480. self.proj1group2 = event.groups[1]
  481. self.defaultenv = Environment.objects.get(name=defaultenv)
  482. def test_range_groups_single(self):
  483. from sentry.snuba.dataset import Dataset
  484. now = (datetime.utcnow() - timedelta(days=1)).replace(
  485. hour=10, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC
  486. )
  487. dts = [now + timedelta(hours=i) for i in range(4)]
  488. project = self.create_project()
  489. group_fingerprint = f"{GroupType.PERFORMANCE_N_PLUS_ONE.value}-group3"
  490. # not sure what's going on here, but `times=1,2,3,4` work fine
  491. # fails with anything above 4
  492. times = 4
  493. event_ids = []
  494. events = []
  495. for i in range(0, times):
  496. res = self.store_transaction(
  497. environment=None,
  498. project_id=project.id,
  499. user_id="my_user",
  500. timestamp=now + timedelta(minutes=i * 10),
  501. fingerprint=[group_fingerprint],
  502. )
  503. grouped_by_project = aliased_query(
  504. dataset=Dataset.Transactions,
  505. start=None,
  506. end=None,
  507. groupby=None,
  508. conditions=None,
  509. filter_keys={"project_id": [project.id], "event_id": [res.event_id]},
  510. selected_columns=["event_id", "project_id", "group_ids"],
  511. aggregations=None,
  512. )
  513. assert grouped_by_project["data"][0]["event_id"] == res.event_id
  514. from sentry.eventstore.models import Event
  515. event_from_nodestore = Event(project_id=project.id, event_id=res.event_id)
  516. assert event_from_nodestore.event_id == res.event_id
  517. event_ids.append(res.event_id)
  518. events.append(res)
  519. group = events[0].groups[0]
  520. transactions_for_project = aliased_query(
  521. dataset=Dataset.Transactions,
  522. start=None,
  523. end=None,
  524. groupby=None,
  525. conditions=None,
  526. filter_keys={"project_id": [project.id]},
  527. selected_columns=["project_id", "event_id"],
  528. aggregations=None,
  529. )
  530. assert len(transactions_for_project["data"]) == times
  531. transactions_by_group = aliased_query(
  532. dataset=Dataset.Transactions,
  533. start=None,
  534. end=None,
  535. # start=group.first_seen,
  536. # end=now + timedelta(hours=4),
  537. groupby=["group_id"],
  538. conditions=None,
  539. filter_keys={"project_id": [project.id], "group_id": [group.id]},
  540. aggregations=[
  541. ["arrayJoin", ["group_ids"], "group_id"],
  542. ["count()", "", "times_seen"],
  543. ],
  544. )
  545. assert transactions_by_group["data"][0]["times_seen"] == times # 1 + (times % 5)
  546. assert self.db.get_range(
  547. TSDBModel.group_performance,
  548. [group.id],
  549. dts[0],
  550. dts[-1],
  551. rollup=3600,
  552. ) == {
  553. group.id: [
  554. # (timestamp(dts[0]), 1 + (times % 5)),
  555. (timestamp(dts[0]), times),
  556. (timestamp(dts[1]), 0),
  557. (timestamp(dts[2]), 0),
  558. (timestamp(dts[3]), 0),
  559. ]
  560. }
  561. def test_range_groups_mult(self):
  562. now = (datetime.utcnow() - timedelta(days=1)).replace(
  563. hour=10, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC
  564. )
  565. dts = [now + timedelta(hours=i) for i in range(4)]
  566. project = self.create_project()
  567. group_fingerprint = f"{GroupType.PERFORMANCE_N_PLUS_ONE.value}-group4"
  568. ids = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5"]
  569. events = []
  570. for i, _ in enumerate(ids):
  571. event = self.store_transaction(
  572. environment=None,
  573. project_id=project.id,
  574. user_id="my_user",
  575. timestamp=now + timedelta(minutes=i * 10),
  576. fingerprint=[group_fingerprint],
  577. )
  578. events.append(event)
  579. group = events[0].groups[0]
  580. assert self.db.get_range(
  581. TSDBModel.group_performance,
  582. [group.id],
  583. dts[0],
  584. dts[-1],
  585. rollup=3600,
  586. ) == {
  587. group.id: [
  588. (timestamp(dts[0]), 6),
  589. (timestamp(dts[1]), 5),
  590. (timestamp(dts[2]), 0),
  591. (timestamp(dts[3]), 0),
  592. ]
  593. }
  594. def test_range_groups_simple(self):
  595. project = self.create_project()
  596. now = (datetime.utcnow() - timedelta(days=1)).replace(
  597. hour=10, minute=0, second=0, microsecond=0, tzinfo=pytz.UTC
  598. )
  599. group_fingerprint = f"{GroupType.PERFORMANCE_SLOW_SPAN.value}-group5"
  600. # for r in range(0, 14400, 600): # Every 10 min for 4 hours
  601. # for r in [1, 2, 3, 4, 5, 6, 7, 8]:
  602. ids = ["a", "b", "c", "d", "e"] # , "f"]
  603. events = []
  604. for r in ids:
  605. # for r in range(0, 9, 1):
  606. event = self.store_transaction(
  607. environment=None,
  608. project_id=project.id,
  609. # change every 55 min so some hours have 1 user, some have 2
  610. user_id=f"user{r}",
  611. # release_version=str(r // 3600) * 10, # 1 per hour,
  612. timestamp=now,
  613. fingerprint=[group_fingerprint],
  614. )
  615. events.append(event)
  616. group = events[0].groups[0]
  617. dts = [now + timedelta(hours=i) for i in range(4)]
  618. assert self.db.get_range(
  619. TSDBModel.group_performance,
  620. [group.id],
  621. dts[0],
  622. dts[-1],
  623. rollup=3600,
  624. ) == {
  625. group.id: [
  626. (timestamp(dts[0]), len(ids)),
  627. (timestamp(dts[1]), 0),
  628. (timestamp(dts[2]), 0),
  629. (timestamp(dts[3]), 0),
  630. ]
  631. }
  632. def test_range_groups(self):
  633. dts = [self.now + timedelta(hours=i) for i in range(4)]
  634. # Multiple groups
  635. assert self.db.get_range(
  636. TSDBModel.group_performance,
  637. [self.proj1group1.id, self.proj1group2.id],
  638. dts[0],
  639. dts[-1],
  640. rollup=3600,
  641. ) == {
  642. self.proj1group1.id: [
  643. (timestamp(dts[0]), 3),
  644. (timestamp(dts[1]), 3),
  645. (timestamp(dts[2]), 3),
  646. (timestamp(dts[3]), 3),
  647. ],
  648. self.proj1group2.id: [
  649. (timestamp(dts[0]), 3),
  650. (timestamp(dts[1]), 3),
  651. (timestamp(dts[2]), 3),
  652. (timestamp(dts[3]), 3),
  653. ],
  654. }
  655. assert (
  656. self.db.get_range(TSDBModel.group_performance, [], dts[0], dts[-1], rollup=3600) == {}
  657. )
  658. class AddJitterToSeriesTest(TestCase):
  659. def setUp(self):
  660. self.db = SnubaTSDB()
  661. def run_test(self, end, interval, jitter, expected_start, expected_end):
  662. end = end.replace(tzinfo=pytz.UTC)
  663. start = end - interval
  664. rollup, rollup_series = self.db.get_optimal_rollup_series(start, end)
  665. series = self.db._add_jitter_to_series(rollup_series, start, rollup, jitter)
  666. assert to_datetime(series[0]) == expected_start.replace(tzinfo=pytz.UTC)
  667. assert to_datetime(series[-1]) == expected_end.replace(tzinfo=pytz.UTC)
  668. def test(self):
  669. self.run_test(
  670. end=datetime(2022, 5, 18, 10, 23, 4),
  671. interval=timedelta(hours=1),
  672. jitter=5,
  673. expected_start=datetime(2022, 5, 18, 9, 22, 55),
  674. expected_end=datetime(2022, 5, 18, 10, 22, 55),
  675. )
  676. self.run_test(
  677. end=datetime(2022, 5, 18, 10, 23, 8),
  678. interval=timedelta(hours=1),
  679. jitter=5,
  680. expected_start=datetime(2022, 5, 18, 9, 23, 5),
  681. expected_end=datetime(2022, 5, 18, 10, 23, 5),
  682. )
  683. # Jitter should be the same
  684. self.run_test(
  685. end=datetime(2022, 5, 18, 10, 23, 8),
  686. interval=timedelta(hours=1),
  687. jitter=55,
  688. expected_start=datetime(2022, 5, 18, 9, 23, 5),
  689. expected_end=datetime(2022, 5, 18, 10, 23, 5),
  690. )
  691. self.run_test(
  692. end=datetime(2022, 5, 18, 22, 33, 2),
  693. interval=timedelta(minutes=1),
  694. jitter=3,
  695. expected_start=datetime(2022, 5, 18, 22, 31, 53),
  696. expected_end=datetime(2022, 5, 18, 22, 32, 53),
  697. )
  698. def test_empty_series(self):
  699. assert self.db._add_jitter_to_series([], datetime(2022, 5, 18, 10, 23, 4), 60, 127) == []
  700. assert self.db._add_jitter_to_series([], datetime(2022, 5, 18, 10, 23, 4), 60, None) == []