test_tsdb_backend.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. from datetime import UTC, datetime, timedelta
  2. from unittest.mock import patch
  3. from snuba_sdk import Limit
  4. from sentry.issues.grouptype import ProfileFileIOGroupType
  5. from sentry.models.environment import Environment
  6. from sentry.models.group import Group
  7. from sentry.models.grouprelease import GroupRelease
  8. from sentry.models.release import Release
  9. from sentry.testutils.cases import SnubaTestCase, TestCase
  10. from sentry.testutils.helpers.datetime import before_now
  11. from sentry.tsdb.base import TSDBModel
  12. from sentry.tsdb.snuba import SnubaTSDB
  13. from sentry.utils.dates import to_datetime
  14. from tests.sentry.issues.test_utils import SearchIssueTestMixin
  15. def timestamp(d):
  16. t = int(d.timestamp())
  17. return t - (t % 3600)
  18. def has_shape(data, shape):
  19. """
  20. Determine if a data object has the provided shape
  21. At any level, the object in `data` and in `shape` must have the same type.
  22. A dict is the same shape if all its keys and values have the same shape as the
  23. key/value in `shape`. The number of keys/values is not relevant.
  24. A list is the same shape if all its items have the same shape as the value
  25. in `shape`
  26. A tuple is the same shape if it has the same length as `shape` and all the
  27. values have the same shape as the corresponding value in `shape`
  28. Any other object simply has to have the same type.
  29. """
  30. assert isinstance(data, type(shape))
  31. if isinstance(data, dict):
  32. return (
  33. len(data) > 0
  34. and all(has_shape(k, list(shape.keys())[0]) for k in data.keys())
  35. and all(has_shape(v, list(shape.values())[0]) for v in data.values())
  36. )
  37. elif isinstance(data, list):
  38. return len(data) > 0 and all(has_shape(v, shape[0]) for v in data)
  39. elif isinstance(data, tuple):
  40. return len(data) == len(shape) and all(
  41. has_shape(data[i], shape[i]) for i in range(len(data))
  42. )
  43. else:
  44. return True
  45. class SnubaTSDBTest(TestCase, SnubaTestCase):
  46. def setUp(self):
  47. super().setUp()
  48. self.db = SnubaTSDB()
  49. self.now = before_now(hours=4).replace(hour=0, minute=0, second=0, microsecond=0)
  50. self.proj1 = self.create_project()
  51. env1 = "test"
  52. env2 = "dev"
  53. defaultenv = ""
  54. release1 = "1" * 10
  55. release2 = "2" * 10
  56. self.release1 = Release.objects.create(
  57. organization_id=self.organization.id, version=release1, date_added=self.now
  58. )
  59. self.release1.add_project(self.proj1)
  60. self.release2 = Release.objects.create(
  61. organization_id=self.organization.id, version=release2, date_added=self.now
  62. )
  63. self.release2.add_project(self.proj1)
  64. for r in range(0, 14400, 600): # Every 10 min for 4 hours
  65. self.store_event(
  66. data={
  67. "event_id": (str(r) * 32)[:32],
  68. "message": "message 1",
  69. "platform": "python",
  70. "fingerprint": [["group-1"], ["group-2"]][
  71. (r // 600) % 2
  72. ], # Switch every 10 mins
  73. "timestamp": (self.now + timedelta(seconds=r)).isoformat(),
  74. "tags": {
  75. "foo": "bar",
  76. "baz": "quux",
  77. "region": ["US", "EU"][(r // 7200) % 3],
  78. # Switch every 2 hours
  79. "environment": [env1, None][(r // 7200) % 3],
  80. "sentry:user": f"id:user{r // 3300}",
  81. },
  82. "user": {
  83. # change every 55 min so some hours have 1 user, some have 2
  84. "id": f"user{r // 3300}",
  85. },
  86. "release": str(r // 3600) * 10, # 1 per hour,
  87. },
  88. project_id=self.proj1.id,
  89. )
  90. groups = Group.objects.filter(project=self.proj1).order_by("id")
  91. self.proj1group1 = groups[0]
  92. self.proj1group2 = groups[1]
  93. self.env1 = Environment.objects.get(name=env1)
  94. self.env2 = self.create_environment(name=env2) # No events
  95. self.defaultenv = Environment.objects.get(name=defaultenv)
  96. self.group1release1env1 = GroupRelease.objects.get(
  97. project_id=self.proj1.id,
  98. group_id=self.proj1group1.id,
  99. release_id=self.release1.id,
  100. environment=env1,
  101. )
  102. self.group1release2env1 = GroupRelease.objects.create(
  103. project_id=self.proj1.id,
  104. group_id=self.proj1group1.id,
  105. release_id=self.release2.id,
  106. environment=env1,
  107. )
  108. self.group2release1env1 = GroupRelease.objects.get(
  109. project_id=self.proj1.id,
  110. group_id=self.proj1group2.id,
  111. release_id=self.release1.id,
  112. environment=env1,
  113. )
  114. def test_range_single(self):
  115. env1 = "test"
  116. project = self.create_project()
  117. for r in range(0, 600 * 6 * 4, 300): # Every 10 min for 4 hours
  118. self.store_event(
  119. data={
  120. "event_id": (str(r) * 32)[:32],
  121. "message": "message 1",
  122. "platform": "python",
  123. "fingerprint": ["group-1"],
  124. "timestamp": (self.now + timedelta(seconds=r)).isoformat(),
  125. "tags": {
  126. "foo": "bar",
  127. "baz": "quux",
  128. # Switch every 2 hours
  129. "region": "US",
  130. "environment": [env1, None][(r // 7200) % 3],
  131. "sentry:user": f"id:user{r // 3300}",
  132. },
  133. "user": {
  134. # change every 55 min so some hours have 1 user, some have 2
  135. "id": f"user{r // 3300}",
  136. },
  137. "release": str(r // 3600) * 10, # 1 per hour,
  138. },
  139. project_id=project.id,
  140. )
  141. groups = Group.objects.filter(project=project).order_by("id")
  142. group = groups[0]
  143. dts = [self.now + timedelta(hours=i) for i in range(4)]
  144. assert self.db.get_range(
  145. TSDBModel.group,
  146. [group.id],
  147. dts[0],
  148. dts[-1],
  149. rollup=3600,
  150. tenant_ids={"referrer": "r", "organization_id": 1234},
  151. ) == {
  152. group.id: [
  153. (timestamp(dts[0]), 6 * 2),
  154. (timestamp(dts[1]), 6 * 2),
  155. (timestamp(dts[2]), 6 * 2),
  156. (timestamp(dts[3]), 6 * 2),
  157. ]
  158. }
  159. def test_range_groups(self):
  160. dts = [self.now + timedelta(hours=i) for i in range(4)]
  161. assert self.db.get_range(
  162. TSDBModel.group,
  163. [self.proj1group1.id],
  164. dts[0],
  165. dts[-1],
  166. rollup=3600,
  167. tenant_ids={"referrer": "r", "organization_id": 1234},
  168. ) == {
  169. self.proj1group1.id: [
  170. (timestamp(dts[0]), 3),
  171. (timestamp(dts[1]), 3),
  172. (timestamp(dts[2]), 3),
  173. (timestamp(dts[3]), 3),
  174. ]
  175. }
  176. # Multiple groups
  177. assert self.db.get_range(
  178. TSDBModel.group,
  179. [self.proj1group1.id, self.proj1group2.id],
  180. dts[0],
  181. dts[-1],
  182. rollup=3600,
  183. tenant_ids={"referrer": "r", "organization_id": 1234},
  184. ) == {
  185. self.proj1group1.id: [
  186. (timestamp(dts[0]), 3),
  187. (timestamp(dts[1]), 3),
  188. (timestamp(dts[2]), 3),
  189. (timestamp(dts[3]), 3),
  190. ],
  191. self.proj1group2.id: [
  192. (timestamp(dts[0]), 3),
  193. (timestamp(dts[1]), 3),
  194. (timestamp(dts[2]), 3),
  195. (timestamp(dts[3]), 3),
  196. ],
  197. }
  198. assert (
  199. self.db.get_range(
  200. TSDBModel.group,
  201. [],
  202. dts[0],
  203. dts[-1],
  204. rollup=3600,
  205. tenant_ids={"referrer": "test", "organization_id": 1},
  206. )
  207. == {}
  208. )
  209. def test_range_releases(self):
  210. dts = [self.now + timedelta(hours=i) for i in range(4)]
  211. assert self.db.get_range(
  212. TSDBModel.release,
  213. [self.release1.id],
  214. dts[0],
  215. dts[-1],
  216. rollup=3600,
  217. tenant_ids={"referrer": "r", "organization_id": 1234},
  218. ) == {
  219. self.release1.id: [
  220. (timestamp(dts[0]), 0),
  221. (timestamp(dts[1]), 6),
  222. (timestamp(dts[2]), 0),
  223. (timestamp(dts[3]), 0),
  224. ]
  225. }
  226. def test_range_project(self):
  227. dts = [self.now + timedelta(hours=i) for i in range(4)]
  228. assert self.db.get_range(
  229. TSDBModel.project,
  230. [self.proj1.id],
  231. dts[0],
  232. dts[-1],
  233. rollup=3600,
  234. tenant_ids={"referrer": "r", "organization_id": 1234},
  235. ) == {
  236. self.proj1.id: [
  237. (timestamp(dts[0]), 6),
  238. (timestamp(dts[1]), 6),
  239. (timestamp(dts[2]), 6),
  240. (timestamp(dts[3]), 6),
  241. ]
  242. }
  243. def test_range_environment_filter(self):
  244. dts = [self.now + timedelta(hours=i) for i in range(4)]
  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.env1.id],
  252. tenant_ids={"referrer": "r", "organization_id": 1234},
  253. ) == {
  254. self.proj1.id: [
  255. (timestamp(dts[0]), 6),
  256. (timestamp(dts[1]), 6),
  257. (timestamp(dts[2]), 0),
  258. (timestamp(dts[3]), 0),
  259. ]
  260. }
  261. # No events submitted for env2
  262. assert self.db.get_range(
  263. TSDBModel.project,
  264. [self.proj1.id],
  265. dts[0],
  266. dts[-1],
  267. rollup=3600,
  268. environment_ids=[self.env2.id],
  269. tenant_ids={"referrer": "r", "organization_id": 1234},
  270. ) == {
  271. self.proj1.id: [
  272. (timestamp(dts[0]), 0),
  273. (timestamp(dts[1]), 0),
  274. (timestamp(dts[2]), 0),
  275. (timestamp(dts[3]), 0),
  276. ]
  277. }
  278. # Events submitted with no environment should match default environment
  279. assert self.db.get_range(
  280. TSDBModel.project,
  281. [self.proj1.id],
  282. dts[0],
  283. dts[-1],
  284. rollup=3600,
  285. environment_ids=[self.defaultenv.id],
  286. tenant_ids={"referrer": "r", "organization_id": 1234},
  287. ) == {
  288. self.proj1.id: [
  289. (timestamp(dts[0]), 0),
  290. (timestamp(dts[1]), 0),
  291. (timestamp(dts[2]), 6),
  292. (timestamp(dts[3]), 6),
  293. ]
  294. }
  295. def test_range_rollups(self):
  296. # Daily
  297. daystart = self.now.replace(hour=0) # day buckets start on day boundaries
  298. dts = [daystart + timedelta(days=i) for i in range(2)]
  299. assert self.db.get_range(
  300. TSDBModel.project,
  301. [self.proj1.id],
  302. dts[0],
  303. dts[-1],
  304. rollup=86400,
  305. tenant_ids={"referrer": "r", "organization_id": 1234},
  306. ) == {self.proj1.id: [(timestamp(dts[0]), 24), (timestamp(dts[1]), 0)]}
  307. # Minutely
  308. dts = [self.now + timedelta(minutes=i) for i in range(120)]
  309. # Expect every 10th minute to have a 1, else 0
  310. expected = [(d.timestamp(), 1 if i % 10 == 0 else 0) for i, d in enumerate(dts)]
  311. assert self.db.get_range(
  312. TSDBModel.project,
  313. [self.proj1.id],
  314. dts[0],
  315. dts[-1],
  316. rollup=60,
  317. tenant_ids={"referrer": "r", "organization_id": 1234},
  318. ) == {self.proj1.id: expected}
  319. def test_distinct_counts_series_users(self):
  320. dts = [self.now + timedelta(hours=i) for i in range(4)]
  321. assert self.db.get_distinct_counts_series(
  322. TSDBModel.users_affected_by_group,
  323. [self.proj1group1.id],
  324. dts[0],
  325. dts[-1],
  326. rollup=3600,
  327. tenant_ids={"referrer": "r", "organization_id": 1234},
  328. ) == {
  329. self.proj1group1.id: [
  330. (timestamp(dts[0]), 1),
  331. (timestamp(dts[1]), 1),
  332. (timestamp(dts[2]), 1),
  333. (timestamp(dts[3]), 2),
  334. ]
  335. }
  336. dts = [self.now + timedelta(hours=i) for i in range(4)]
  337. assert self.db.get_distinct_counts_series(
  338. TSDBModel.users_affected_by_project,
  339. [self.proj1.id],
  340. dts[0],
  341. dts[-1],
  342. rollup=3600,
  343. tenant_ids={"referrer": "r", "organization_id": 1234},
  344. ) == {
  345. self.proj1.id: [
  346. (timestamp(dts[0]), 1),
  347. (timestamp(dts[1]), 2),
  348. (timestamp(dts[2]), 2),
  349. (timestamp(dts[3]), 2),
  350. ]
  351. }
  352. assert (
  353. self.db.get_distinct_counts_series(
  354. TSDBModel.users_affected_by_group,
  355. [],
  356. dts[0],
  357. dts[-1],
  358. rollup=3600,
  359. tenant_ids={"referrer": "r", "organization_id": 1234},
  360. )
  361. == {}
  362. )
  363. def test_get_distinct_counts_totals_users(self):
  364. assert self.db.get_distinct_counts_totals(
  365. TSDBModel.users_affected_by_group,
  366. [self.proj1group1.id],
  367. self.now,
  368. self.now + timedelta(hours=4),
  369. rollup=3600,
  370. tenant_ids={"referrer": "r", "organization_id": 1234},
  371. ) == {
  372. self.proj1group1.id: 5 # 5 unique users overall
  373. }
  374. assert self.db.get_distinct_counts_totals(
  375. TSDBModel.users_affected_by_group,
  376. [self.proj1group1.id],
  377. self.now,
  378. self.now,
  379. rollup=3600,
  380. tenant_ids={"referrer": "r", "organization_id": 1234},
  381. ) == {
  382. self.proj1group1.id: 1 # Only 1 unique user in the first hour
  383. }
  384. assert self.db.get_distinct_counts_totals(
  385. TSDBModel.users_affected_by_project,
  386. [self.proj1.id],
  387. self.now,
  388. self.now + timedelta(hours=4),
  389. rollup=3600,
  390. tenant_ids={"referrer": "r", "organization_id": 1234},
  391. ) == {self.proj1.id: 5}
  392. assert (
  393. self.db.get_distinct_counts_totals(
  394. TSDBModel.users_affected_by_group,
  395. [],
  396. self.now,
  397. self.now + timedelta(hours=4),
  398. rollup=3600,
  399. tenant_ids={"referrer": "r", "organization_id": 1234},
  400. )
  401. == {}
  402. )
  403. def test_get_distinct_counts_totals_users_with_conditions(self):
  404. assert self.db.get_distinct_counts_totals_with_conditions(
  405. TSDBModel.users_affected_by_group,
  406. [self.proj1group1.id],
  407. self.now,
  408. self.now + timedelta(hours=4),
  409. rollup=3600,
  410. tenant_ids={"referrer": "r", "organization_id": 1234},
  411. conditions=[("tags[region]", "=", "US")],
  412. ) == {
  413. self.proj1group1.id: 2 # 5 unique users with US tag
  414. }
  415. assert self.db.get_distinct_counts_totals_with_conditions(
  416. TSDBModel.users_affected_by_group,
  417. [self.proj1group1.id],
  418. self.now,
  419. self.now + timedelta(hours=4),
  420. rollup=3600,
  421. tenant_ids={"referrer": "r", "organization_id": 1234},
  422. conditions=[("tags[region]", "=", "EU")],
  423. ) == {
  424. self.proj1group1.id: 3 # 3 unique users with EU tag
  425. }
  426. assert self.db.get_distinct_counts_totals_with_conditions(
  427. TSDBModel.users_affected_by_group,
  428. [self.proj1group1.id],
  429. self.now,
  430. self.now + timedelta(hours=4),
  431. rollup=3600,
  432. tenant_ids={"referrer": "r", "organization_id": 1234},
  433. conditions=[("tags[region]", "=", "MARS")],
  434. ) == {self.proj1group1.id: 0}
  435. assert (
  436. self.db.get_distinct_counts_totals_with_conditions(
  437. TSDBModel.users_affected_by_group,
  438. [],
  439. self.now,
  440. self.now + timedelta(hours=4),
  441. rollup=3600,
  442. tenant_ids={"referrer": "r", "organization_id": 1234},
  443. )
  444. == {}
  445. )
  446. def test_frequency_series(self):
  447. dts = [self.now + timedelta(hours=i) for i in range(4)]
  448. assert self.db.get_frequency_series(
  449. TSDBModel.frequent_releases_by_group,
  450. {
  451. self.proj1group1.id: (self.group1release1env1.id, self.group1release2env1.id),
  452. self.proj1group2.id: (self.group2release1env1.id,),
  453. },
  454. dts[0],
  455. dts[-1],
  456. rollup=3600,
  457. tenant_ids={"referrer": "r", "organization_id": 1234},
  458. ) == {
  459. self.proj1group1.id: [
  460. (timestamp(dts[0]), {self.group1release1env1.id: 0, self.group1release2env1.id: 0}),
  461. (timestamp(dts[1]), {self.group1release1env1.id: 3, self.group1release2env1.id: 0}),
  462. (timestamp(dts[2]), {self.group1release1env1.id: 0, self.group1release2env1.id: 3}),
  463. (timestamp(dts[3]), {self.group1release1env1.id: 0, self.group1release2env1.id: 0}),
  464. ],
  465. self.proj1group2.id: [
  466. (timestamp(dts[0]), {self.group2release1env1.id: 0}),
  467. (timestamp(dts[1]), {self.group2release1env1.id: 3}),
  468. (timestamp(dts[2]), {self.group2release1env1.id: 0}),
  469. (timestamp(dts[3]), {self.group2release1env1.id: 0}),
  470. ],
  471. }
  472. assert (
  473. self.db.get_frequency_series(
  474. TSDBModel.frequent_releases_by_group,
  475. {},
  476. dts[0],
  477. dts[-1],
  478. rollup=3600,
  479. tenant_ids={"referrer": "r", "organization_id": 1234},
  480. )
  481. == {}
  482. )
  483. def test_result_shape(self):
  484. """
  485. Tests that the results from the different TSDB methods have the
  486. expected format.
  487. """
  488. project_id = self.proj1.id
  489. dts = [self.now + timedelta(hours=i) for i in range(4)]
  490. items = {
  491. # {project_id: (issue_id, issue_id, ...)}
  492. project_id: (self.proj1group1.id, self.proj1group2.id)
  493. }
  494. results1 = self.db.get_frequency_series(
  495. TSDBModel.frequent_issues_by_project,
  496. items,
  497. dts[0],
  498. dts[-1],
  499. tenant_ids={"referrer": "r", "organization_id": 1234},
  500. )
  501. assert has_shape(results1, {1: [(1, {1: 1})]})
  502. results2 = self.db.get_range(
  503. TSDBModel.project,
  504. [project_id],
  505. dts[0],
  506. dts[-1],
  507. tenant_ids={"referrer": "r", "organization_id": 1234},
  508. )
  509. assert has_shape(results2, {1: [(1, 1)]})
  510. results3 = self.db.get_distinct_counts_series(
  511. TSDBModel.users_affected_by_project,
  512. [project_id],
  513. dts[0],
  514. dts[-1],
  515. tenant_ids={"referrer": "r", "organization_id": 1234},
  516. )
  517. assert has_shape(results3, {1: [(1, 1)]})
  518. results4 = self.db.get_distinct_counts_totals(
  519. TSDBModel.users_affected_by_project,
  520. [project_id],
  521. dts[0],
  522. dts[-1],
  523. tenant_ids={"referrer": "r", "organization_id": 1234},
  524. )
  525. assert has_shape(results4, {1: 1})
  526. def test_calculated_limit(self):
  527. with patch("sentry.tsdb.snuba.raw_snql_query") as snuba:
  528. # 24h test
  529. rollup = 3600
  530. end = self.now
  531. start = end + timedelta(days=-1, seconds=rollup)
  532. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  533. assert snuba.call_args.args[0].query.limit == Limit(120)
  534. # 14 day test
  535. rollup = 86400
  536. start = end + timedelta(days=-14, seconds=rollup)
  537. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  538. assert snuba.call_args.args[0].query.limit == Limit(70)
  539. # 1h test
  540. rollup = 3600
  541. end = self.now
  542. start = end + timedelta(hours=-1, seconds=rollup)
  543. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  544. assert snuba.call_args.args[0].query.limit == Limit(5)
  545. @patch("sentry.utils.snuba.OVERRIDE_OPTIONS", new={"consistent": True})
  546. def test_tsdb_with_consistent(self):
  547. with patch("sentry.utils.snuba._apply_cache_and_build_results") as snuba:
  548. rollup = 3600
  549. end = self.now
  550. start = end + timedelta(days=-1, seconds=rollup)
  551. self.db.get_data(TSDBModel.group, [1, 2, 3, 4, 5], start, end, rollup=rollup)
  552. assert snuba.call_args.args[0][0].request.query.limit == Limit(120)
  553. assert snuba.call_args.args[0][0].request.flags.consistent is True
  554. class SnubaTSDBGroupProfilingTest(TestCase, SnubaTestCase, SearchIssueTestMixin):
  555. def setUp(self):
  556. super().setUp()
  557. self.db = SnubaTSDB()
  558. self.now = before_now(hours=4).replace(hour=0, minute=0, second=0, microsecond=0)
  559. self.proj1 = self.create_project()
  560. self.env1 = Environment.objects.get_or_create(
  561. organization_id=self.proj1.organization_id, name="test"
  562. )[0]
  563. self.env2 = Environment.objects.get_or_create(
  564. organization_id=self.proj1.organization_id, name="dev"
  565. )[0]
  566. defaultenv = ""
  567. group1_fingerprint = f"{ProfileFileIOGroupType.type_id}-group1"
  568. group2_fingerprint = f"{ProfileFileIOGroupType.type_id}-group2"
  569. groups = {}
  570. for r in range(0, 14400, 600): # Every 10 min for 4 hours
  571. event, occurrence, group_info = self.store_search_issue(
  572. project_id=self.proj1.id,
  573. # change every 55 min so some hours have 1 user, some have 2
  574. user_id=r // 3300,
  575. fingerprints=[group1_fingerprint] if ((r // 600) % 2) else [group2_fingerprint],
  576. # release_version=str(r // 3600) * 10, # 1 per hour,
  577. environment=[self.env1.name, None][(r // 7200) % 3],
  578. insert_time=self.now + timedelta(seconds=r),
  579. )
  580. if group_info:
  581. groups[group_info.group.id] = group_info.group
  582. all_groups = list(groups.values())
  583. self.proj1group1 = all_groups[0]
  584. self.proj1group2 = all_groups[1]
  585. self.defaultenv = Environment.objects.get(name=defaultenv)
  586. def test_range_group_manual_group_time_rollup(self):
  587. project = self.create_project()
  588. # these are the only granularities/rollups that be actually be used
  589. GRANULARITIES = [
  590. (10, timedelta(seconds=10), 5),
  591. (60 * 60, timedelta(hours=1), 6),
  592. (60 * 60 * 24, timedelta(days=1), 15),
  593. ]
  594. start = before_now(days=15).replace(hour=0, minute=0, second=0)
  595. for step, delta, times in GRANULARITIES:
  596. series = [start + (delta * i) for i in range(times)]
  597. series_ts = [int(ts.timestamp()) for ts in series]
  598. assert self.db.get_optimal_rollup(series[0], series[-1]) == step
  599. assert self.db.get_optimal_rollup_series(series[0], end=series[-1], rollup=None) == (
  600. step,
  601. series_ts,
  602. )
  603. for time_step in series:
  604. _, _, group_info = self.store_search_issue(
  605. project_id=project.id,
  606. user_id=0,
  607. fingerprints=[f"test_range_group_manual_group_time_rollup-{step}"],
  608. environment=None,
  609. insert_time=time_step,
  610. )
  611. assert group_info is not None
  612. assert self.db.get_range(
  613. TSDBModel.group_generic,
  614. [group_info.group.id],
  615. series[0],
  616. series[-1],
  617. rollup=None,
  618. tenant_ids={"referrer": "test", "organization_id": 1},
  619. ) == {group_info.group.id: [(ts, 1) for ts in series_ts]}
  620. def test_range_groups_mult(self):
  621. now = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  622. dts = [now + timedelta(hours=i) for i in range(4)]
  623. project = self.create_project()
  624. group_fingerprint = f"{ProfileFileIOGroupType.type_id}-group4"
  625. groups = []
  626. for i in range(0, 11):
  627. _, _, group_info = self.store_search_issue(
  628. project_id=project.id,
  629. user_id=0,
  630. fingerprints=[group_fingerprint],
  631. environment=None,
  632. insert_time=now + timedelta(minutes=i * 10),
  633. )
  634. if group_info:
  635. groups.append(group_info.group)
  636. group = groups[0]
  637. assert self.db.get_range(
  638. TSDBModel.group_generic,
  639. [group.id],
  640. dts[0],
  641. dts[-1],
  642. rollup=3600,
  643. tenant_ids={"referrer": "test", "organization_id": 1},
  644. ) == {
  645. group.id: [
  646. (timestamp(dts[0]), 6),
  647. (timestamp(dts[1]), 5),
  648. (timestamp(dts[2]), 0),
  649. (timestamp(dts[3]), 0),
  650. ]
  651. }
  652. def test_range_groups_simple(self):
  653. project = self.create_project()
  654. now = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  655. group_fingerprint = f"{ProfileFileIOGroupType.type_id}-group5"
  656. ids = [1, 2, 3, 4, 5]
  657. groups = []
  658. for r in ids:
  659. # for r in range(0, 9, 1):
  660. event, occurrence, group_info = self.store_search_issue(
  661. project_id=project.id,
  662. # change every 55 min so some hours have 1 user, some have 2
  663. user_id=r,
  664. fingerprints=[group_fingerprint],
  665. environment=None,
  666. # release_version=str(r // 3600) * 10, # 1 per hour,
  667. insert_time=now,
  668. )
  669. if group_info:
  670. groups.append(group_info.group)
  671. group = groups[0]
  672. dts = [now + timedelta(hours=i) for i in range(4)]
  673. assert self.db.get_range(
  674. TSDBModel.group_generic,
  675. [group.id],
  676. dts[0],
  677. dts[-1],
  678. rollup=3600,
  679. tenant_ids={"referrer": "test", "organization_id": 1},
  680. ) == {
  681. group.id: [
  682. (timestamp(dts[0]), len(ids)),
  683. (timestamp(dts[1]), 0),
  684. (timestamp(dts[2]), 0),
  685. (timestamp(dts[3]), 0),
  686. ]
  687. }
  688. def test_range_groups(self):
  689. dts = [self.now + timedelta(hours=i) for i in range(4)]
  690. # Multiple groups
  691. assert self.db.get_range(
  692. TSDBModel.group_generic,
  693. [self.proj1group1.id, self.proj1group2.id],
  694. dts[0],
  695. dts[-1],
  696. rollup=3600,
  697. tenant_ids={"referrer": "test", "organization_id": 1},
  698. ) == {
  699. self.proj1group1.id: [
  700. (timestamp(dts[0]), 3),
  701. (timestamp(dts[1]), 3),
  702. (timestamp(dts[2]), 3),
  703. (timestamp(dts[3]), 3),
  704. ],
  705. self.proj1group2.id: [
  706. (timestamp(dts[0]), 3),
  707. (timestamp(dts[1]), 3),
  708. (timestamp(dts[2]), 3),
  709. (timestamp(dts[3]), 3),
  710. ],
  711. }
  712. assert (
  713. self.db.get_range(
  714. TSDBModel.group_generic,
  715. [],
  716. dts[0],
  717. dts[-1],
  718. rollup=3600,
  719. tenant_ids={"referrer": "test", "organization_id": 1},
  720. )
  721. == {}
  722. )
  723. def test_get_distinct_counts_totals_users(self):
  724. assert self.db.get_distinct_counts_totals(
  725. TSDBModel.users_affected_by_generic_group,
  726. [self.proj1group1.id],
  727. self.now,
  728. self.now + timedelta(hours=4),
  729. rollup=3600,
  730. tenant_ids={"referrer": "test", "organization_id": 1},
  731. ) == {
  732. self.proj1group1.id: 5 # 5 unique users overall
  733. }
  734. assert self.db.get_distinct_counts_totals(
  735. TSDBModel.users_affected_by_generic_group,
  736. [self.proj1group1.id],
  737. self.now,
  738. self.now,
  739. rollup=3600,
  740. tenant_ids={"referrer": "test", "organization_id": 1},
  741. ) == {
  742. self.proj1group1.id: 1 # Only 1 unique user in the first hour
  743. }
  744. assert (
  745. self.db.get_distinct_counts_totals(
  746. TSDBModel.users_affected_by_generic_group,
  747. [],
  748. self.now,
  749. self.now + timedelta(hours=4),
  750. rollup=3600,
  751. tenant_ids={"referrer": "test", "organization_id": 1},
  752. )
  753. == {}
  754. )
  755. def test_get_sums(self):
  756. assert self.db.get_sums(
  757. model=TSDBModel.group_generic,
  758. keys=[self.proj1group1.id, self.proj1group2.id],
  759. start=self.now,
  760. end=self.now + timedelta(hours=4),
  761. tenant_ids={"referrer": "test", "organization_id": 1},
  762. ) == {self.proj1group1.id: 12, self.proj1group2.id: 12}
  763. def test_get_data_or_conditions_parsed(self):
  764. """
  765. Verify parsing the legacy format with nested OR conditions works
  766. """
  767. conditions = [
  768. # or conditions in the legacy format needs open and close brackets for precedence
  769. # there's some special casing when parsing conditions that specifically handles this
  770. [
  771. [["isNull", ["environment"]], "=", 1],
  772. ["environment", "IN", [self.env1.name]],
  773. ]
  774. ]
  775. data1 = self.db.get_data(
  776. model=TSDBModel.group_generic,
  777. keys=[self.proj1group1.id, self.proj1group2.id],
  778. conditions=conditions,
  779. start=self.now,
  780. end=self.now + timedelta(hours=4),
  781. tenant_ids={"referrer": "test", "organization_id": 1},
  782. )
  783. data2 = self.db.get_data(
  784. model=TSDBModel.group_generic,
  785. keys=[self.proj1group1.id, self.proj1group2.id],
  786. start=self.now,
  787. end=self.now + timedelta(hours=4),
  788. tenant_ids={"referrer": "test", "organization_id": 1},
  789. )
  790. # the above queries should return the same data since all groups either have:
  791. # environment=None or environment=test
  792. # so the condition really shouldn't be filtering anything
  793. assert data1 == data2
  794. class AddJitterToSeriesTest(TestCase):
  795. def setUp(self):
  796. self.db = SnubaTSDB()
  797. def run_test(self, end, interval, jitter, expected_start, expected_end):
  798. start = end - interval
  799. rollup, rollup_series = self.db.get_optimal_rollup_series(start, end)
  800. series = self.db._add_jitter_to_series(rollup_series, start, rollup, jitter)
  801. assert to_datetime(series[0]) == expected_start
  802. assert to_datetime(series[-1]) == expected_end
  803. def test(self):
  804. self.run_test(
  805. end=datetime(2022, 5, 18, 10, 23, 4, tzinfo=UTC),
  806. interval=timedelta(hours=1),
  807. jitter=5,
  808. expected_start=datetime(2022, 5, 18, 9, 22, 55, tzinfo=UTC),
  809. expected_end=datetime(2022, 5, 18, 10, 22, 55, tzinfo=UTC),
  810. )
  811. self.run_test(
  812. end=datetime(2022, 5, 18, 10, 23, 8, tzinfo=UTC),
  813. interval=timedelta(hours=1),
  814. jitter=5,
  815. expected_start=datetime(2022, 5, 18, 9, 23, 5, tzinfo=UTC),
  816. expected_end=datetime(2022, 5, 18, 10, 23, 5, tzinfo=UTC),
  817. )
  818. # Jitter should be the same
  819. self.run_test(
  820. end=datetime(2022, 5, 18, 10, 23, 8, tzinfo=UTC),
  821. interval=timedelta(hours=1),
  822. jitter=55,
  823. expected_start=datetime(2022, 5, 18, 9, 23, 5, tzinfo=UTC),
  824. expected_end=datetime(2022, 5, 18, 10, 23, 5, tzinfo=UTC),
  825. )
  826. self.run_test(
  827. end=datetime(2022, 5, 18, 22, 33, 2, tzinfo=UTC),
  828. interval=timedelta(minutes=1),
  829. jitter=3,
  830. expected_start=datetime(2022, 5, 18, 22, 31, 53, tzinfo=UTC),
  831. expected_end=datetime(2022, 5, 18, 22, 32, 53, tzinfo=UTC),
  832. )
  833. def test_empty_series(self):
  834. assert self.db._add_jitter_to_series([], datetime(2022, 5, 18, 10, 23, 4), 60, 127) == []
  835. assert self.db._add_jitter_to_series([], datetime(2022, 5, 18, 10, 23, 4), 60, None) == []