test_organization_sessions.py 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359
  1. import datetime
  2. from unittest.mock import patch
  3. from uuid import uuid4
  4. import pytest
  5. from django.urls import reverse
  6. from django.utils import timezone
  7. from sentry.models.releaseprojectenvironment import ReleaseProjectEnvironment
  8. from sentry.release_health.metrics import MetricsReleaseHealthBackend
  9. from sentry.snuba.metrics import to_intervals
  10. from sentry.testutils.cases import APITestCase, BaseMetricsTestCase
  11. from sentry.testutils.helpers.datetime import freeze_time
  12. from sentry.testutils.helpers.link_header import parse_link_header
  13. from sentry.utils.cursors import Cursor
  14. pytestmark = pytest.mark.sentry_metrics
  15. def result_sorted(result):
  16. """sort the groups of the results array by the `by` object, ensuring a stable order"""
  17. def stable_dict(d):
  18. return tuple(sorted(d.items(), key=lambda t: t[0]))
  19. result["groups"].sort(key=lambda group: stable_dict(group["by"]))
  20. return result
  21. ONE_DAY_AGO = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(days=1)
  22. TWO_DAYS_AGO = datetime.datetime.now(tz=datetime.UTC) - datetime.timedelta(days=2)
  23. MOCK_DATETIME = ONE_DAY_AGO.replace(hour=12, minute=27, second=28, microsecond=303000)
  24. MOCK_DATETIME_PLUS_TEN_MINUTES = MOCK_DATETIME + datetime.timedelta(minutes=10)
  25. MOCK_DATETIME_PLUS_ONE_HOUR = MOCK_DATETIME + datetime.timedelta(hours=1)
  26. SNUBA_TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
  27. MOCK_DATETIME_START_OF_DAY = MOCK_DATETIME.replace(hour=0, minute=0, second=0)
  28. TIMESTAMP = MOCK_DATETIME.timestamp()
  29. RECEIVED = TIMESTAMP
  30. SESSION_STARTED = TIMESTAMP // 3600 * 3600 # round to the hour
  31. TEMPLATE = {
  32. "distinct_id": "00000000-0000-0000-0000-000000000000",
  33. "status": "exited",
  34. "seq": 0,
  35. "release": "foo@1.0.0",
  36. "environment": "production",
  37. "retention_days": 90,
  38. "duration": 123.4,
  39. "errors": 0,
  40. "started": SESSION_STARTED,
  41. "received": RECEIVED,
  42. }
  43. def make_duration(kwargs):
  44. """Randomish but deterministic duration"""
  45. return float(len(str(kwargs)))
  46. def make_session(project, **kwargs):
  47. return dict(
  48. dict(
  49. TEMPLATE,
  50. session_id=uuid4().hex,
  51. org_id=project.organization_id,
  52. project_id=project.id,
  53. duration=make_duration(kwargs),
  54. ),
  55. **kwargs,
  56. )
  57. def adjust_start(start: datetime.datetime, interval: int) -> datetime.datetime:
  58. # align start and end to the beginning of the intervals
  59. start, _end, _num_intervals = to_intervals(
  60. start, start + datetime.timedelta(minutes=1), interval
  61. )
  62. return start
  63. def adjust_end(end: datetime.datetime, interval: int) -> datetime.datetime:
  64. # align start and end to the beginning of the intervals
  65. _start, end, _num_intervals = to_intervals(end - datetime.timedelta(minutes=1), end, interval)
  66. return end
  67. class OrganizationSessionsEndpointTest(APITestCase, BaseMetricsTestCase):
  68. def setUp(self):
  69. super().setUp()
  70. self.setup_fixture()
  71. def setup_fixture(self):
  72. self.organization1 = self.organization
  73. self.organization2 = self.create_organization()
  74. self.organization3 = self.create_organization()
  75. self.project1 = self.project
  76. self.project2 = self.create_project()
  77. self.project3 = self.create_project()
  78. self.project4 = self.create_project(organization=self.organization2)
  79. self.user2 = self.create_user(is_superuser=False)
  80. self.create_member(
  81. user=self.user2, organization=self.organization1, role="member", teams=[]
  82. )
  83. self.create_member(user=self.user, organization=self.organization3, role="admin", teams=[])
  84. self.create_environment(self.project2, name="development")
  85. self.bulk_store_sessions(
  86. [
  87. make_session(self.project1, started=SESSION_STARTED + 12 * 60),
  88. make_session(self.project1, started=SESSION_STARTED + 24 * 60, release="foo@1.1.0"),
  89. make_session(self.project1, started=SESSION_STARTED - 60 * 60),
  90. make_session(self.project1, started=SESSION_STARTED - 12 * 60 * 60),
  91. make_session(self.project2, status="crashed"),
  92. make_session(self.project2, environment="development"),
  93. make_session(self.project3, errors=1, release="foo@1.2.0"),
  94. make_session(
  95. self.project3,
  96. distinct_id="39887d89-13b2-4c84-8c23-5d13d2102664",
  97. started=SESSION_STARTED - 60 * 60,
  98. ),
  99. make_session(
  100. self.project3, distinct_id="39887d89-13b2-4c84-8c23-5d13d2102664", errors=1
  101. ),
  102. make_session(self.project4),
  103. ]
  104. )
  105. def do_request(self, query, user=None, org=None):
  106. self.login_as(user=user or self.user)
  107. url = reverse(
  108. "sentry-api-0-organization-sessions",
  109. kwargs={"organization_id_or_slug": (org or self.organization).slug},
  110. )
  111. return self.client.get(url, query, format="json")
  112. def test_empty_request(self):
  113. response = self.do_request({})
  114. assert response.status_code == 400, response.content
  115. assert response.data == {"detail": 'Request is missing a "field"'}
  116. def test_inaccessible_project(self):
  117. response = self.do_request({"project": [self.project4.id]})
  118. assert response.status_code == 403, response.content
  119. assert response.data == {"detail": "You do not have permission to perform this action."}
  120. def test_unknown_field(self):
  121. response = self.do_request({"field": ["summ(session)"]})
  122. assert response.status_code == 400, response.content
  123. assert response.data == {"detail": 'Invalid field: "summ(session)"'}
  124. def test_unknown_groupby(self):
  125. response = self.do_request({"field": ["sum(session)"], "groupBy": ["environment_"]})
  126. assert response.status_code == 400, response.content
  127. assert response.data == {"detail": 'Invalid groupBy: "environment_"'}
  128. def test_illegal_groupby(self):
  129. response = self.do_request({"field": ["sum(session)"], "groupBy": ["issue.id"]})
  130. assert response.status_code == 400, response.content
  131. assert response.data == {"detail": 'Invalid groupBy: "issue.id"'}
  132. def test_invalid_query(self):
  133. response = self.do_request(
  134. {"statsPeriod": "1d", "field": ["sum(session)"], "query": ["foo:bar"]}
  135. )
  136. assert response.status_code == 400, response.content
  137. assert response.data["detail"] == "Invalid search filter: foo"
  138. response = self.do_request(
  139. {
  140. "statsPeriod": "1d",
  141. "field": ["sum(session)"],
  142. "query": ["release:foo-bar@1.2.3 (123)"],
  143. }
  144. )
  145. assert response.status_code == 400, response.content
  146. # TODO: it would be good to provide a better error here,
  147. # since its not obvious where `message` comes from.
  148. assert response.data["detail"] == "Invalid search filter: message"
  149. def test_illegal_query(self):
  150. response = self.do_request(
  151. {"statsPeriod": "1d", "field": ["sum(session)"], "query": ["issue.id:123"]}
  152. )
  153. assert response.status_code == 400, response.content
  154. assert response.data["detail"] == "Invalid search filter: issue.id"
  155. def test_too_many_points(self):
  156. # default statsPeriod is 90d
  157. response = self.do_request({"field": ["sum(session)"], "interval": "1h"})
  158. assert response.status_code == 400, response.content
  159. assert response.data == {
  160. "detail": "Your interval and date range would create too many results. "
  161. "Use a larger interval, or a smaller date range."
  162. }
  163. @freeze_time(MOCK_DATETIME)
  164. def test_future_request(self):
  165. start = MOCK_DATETIME + datetime.timedelta(days=1)
  166. end = MOCK_DATETIME + datetime.timedelta(days=2)
  167. response = self.do_request(
  168. {
  169. "project": [-1],
  170. "interval": "1h",
  171. "field": ["sum(session)"],
  172. "start": start.strftime(SNUBA_TIME_FORMAT),
  173. "end": end.strftime(SNUBA_TIME_FORMAT),
  174. }
  175. )
  176. assert response.status_code == 200, response.content
  177. @freeze_time(MOCK_DATETIME)
  178. def test_timeseries_interval(self):
  179. response = self.do_request(
  180. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]}
  181. )
  182. start_of_day_snuba_format = MOCK_DATETIME_START_OF_DAY.strftime(SNUBA_TIME_FORMAT)
  183. previous_start_of_day_snuba_format = (
  184. MOCK_DATETIME_START_OF_DAY - datetime.timedelta(days=1)
  185. ).strftime(SNUBA_TIME_FORMAT)
  186. expected_start = MOCK_DATETIME_START_OF_DAY - datetime.timedelta(days=1)
  187. expected_end = MOCK_DATETIME_START_OF_DAY + datetime.timedelta(days=1)
  188. assert response.status_code == 200, response.content
  189. assert result_sorted(response.data) == {
  190. "start": expected_start.strftime(SNUBA_TIME_FORMAT),
  191. "end": expected_end.strftime(SNUBA_TIME_FORMAT),
  192. "query": "",
  193. "intervals": [previous_start_of_day_snuba_format, start_of_day_snuba_format],
  194. "groups": [
  195. {"by": {}, "series": {"sum(session)": [0, 9]}, "totals": {"sum(session)": 9}}
  196. ],
  197. }
  198. response = self.do_request(
  199. {"project": [-1], "statsPeriod": "1d", "interval": "6h", "field": ["sum(session)"]}
  200. )
  201. six_hours = 6 * 60 * 60
  202. expected_start = adjust_start(TWO_DAYS_AGO.replace(hour=12, minute=0, second=0), six_hours)
  203. expected_end = adjust_end(MOCK_DATETIME.replace(minute=28, second=0), six_hours)
  204. assert response.status_code == 200, response.content
  205. assert result_sorted(response.data) == {
  206. "start": expected_start.strftime(SNUBA_TIME_FORMAT),
  207. "end": expected_end.strftime(SNUBA_TIME_FORMAT),
  208. "query": "",
  209. "intervals": [
  210. TWO_DAYS_AGO.replace(hour=12, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  211. TWO_DAYS_AGO.replace(hour=18, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  212. MOCK_DATETIME.replace(hour=0, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  213. MOCK_DATETIME.replace(hour=6, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  214. MOCK_DATETIME.replace(hour=12, minute=0, second=0).strftime(SNUBA_TIME_FORMAT),
  215. ],
  216. "groups": [
  217. {
  218. "by": {},
  219. "series": {"sum(session)": [0, 0, 1, 2, 6]},
  220. "totals": {"sum(session)": 9},
  221. }
  222. ],
  223. }
  224. @freeze_time(MOCK_DATETIME)
  225. def test_user_all_accessible(self):
  226. response = self.do_request(
  227. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]},
  228. user=self.user2,
  229. )
  230. start_of_previous_day = MOCK_DATETIME_START_OF_DAY - datetime.timedelta(days=1)
  231. start_of_day_snuba_format = MOCK_DATETIME_START_OF_DAY.strftime(SNUBA_TIME_FORMAT)
  232. start_of_previous_day_snuba_format = start_of_previous_day.strftime(SNUBA_TIME_FORMAT)
  233. expected_start = MOCK_DATETIME_START_OF_DAY - datetime.timedelta(days=1)
  234. expected_end = MOCK_DATETIME_START_OF_DAY + datetime.timedelta(days=1)
  235. assert response.status_code == 200, response.content
  236. assert result_sorted(response.data) == {
  237. "start": expected_start.strftime(SNUBA_TIME_FORMAT),
  238. "end": expected_end.strftime(SNUBA_TIME_FORMAT),
  239. "query": "",
  240. "intervals": [start_of_previous_day_snuba_format, start_of_day_snuba_format],
  241. "groups": [
  242. {"by": {}, "series": {"sum(session)": [0, 9]}, "totals": {"sum(session)": 9}}
  243. ],
  244. }
  245. def test_no_projects(self):
  246. response = self.do_request(
  247. {"project": [-1], "statsPeriod": "1d", "interval": "1d", "field": ["sum(session)"]},
  248. org=self.organization3,
  249. )
  250. assert response.status_code == 400, response.content
  251. assert response.data == {"detail": "No projects available"}
  252. @freeze_time(MOCK_DATETIME_PLUS_TEN_MINUTES)
  253. def test_minute_resolution(self):
  254. with self.feature("organizations:minute-resolution-sessions"):
  255. response = self.do_request(
  256. {
  257. "project": [self.project1.id, self.project2.id],
  258. "statsPeriod": "30m",
  259. "interval": "10m",
  260. "field": ["sum(session)"],
  261. }
  262. )
  263. assert response.status_code == 200, response.content
  264. ten_min = 10 * 60
  265. expected_start = adjust_start(
  266. MOCK_DATETIME.replace(hour=12, minute=0, second=0), ten_min
  267. )
  268. expected_end = adjust_end(MOCK_DATETIME.replace(hour=12, minute=38, second=0), ten_min)
  269. assert result_sorted(response.data) == {
  270. "start": expected_start.strftime(SNUBA_TIME_FORMAT),
  271. "end": expected_end.strftime(SNUBA_TIME_FORMAT),
  272. "query": "",
  273. "intervals": [
  274. *[
  275. MOCK_DATETIME.replace(hour=12, minute=min, second=0).strftime(
  276. SNUBA_TIME_FORMAT
  277. )
  278. for min in [0, 10, 20, 30]
  279. ],
  280. ],
  281. "groups": [
  282. {
  283. "by": {},
  284. "series": {"sum(session)": [2, 1, 1, 0]},
  285. "totals": {"sum(session)": 4},
  286. }
  287. ],
  288. }
  289. @freeze_time(MOCK_DATETIME_PLUS_TEN_MINUTES)
  290. def test_10s_resolution(self):
  291. with self.feature("organizations:minute-resolution-sessions"):
  292. response = self.do_request(
  293. {
  294. "project": [self.project1.id],
  295. "statsPeriod": "1m",
  296. "interval": "10s",
  297. "field": ["sum(session)"],
  298. }
  299. )
  300. assert response.status_code == 200, response.content
  301. # With the metrics backend, we should get exactly what we asked for,
  302. # 6 intervals with 10 second length. However, since we add both the
  303. # starting and ending interval we get 7 intervals.
  304. assert len(response.data["intervals"]) == 7
  305. @freeze_time(MOCK_DATETIME)
  306. def test_filter_projects(self):
  307. response = self.do_request(
  308. {
  309. "statsPeriod": "1d",
  310. "interval": "1d",
  311. "field": ["sum(session)"],
  312. "project": [self.project2.id, self.project3.id],
  313. }
  314. )
  315. assert response.status_code == 200, response.content
  316. assert result_sorted(response.data)["groups"] == [
  317. {"by": {}, "series": {"sum(session)": [0, 5]}, "totals": {"sum(session)": 5}}
  318. ]
  319. @freeze_time(MOCK_DATETIME)
  320. def test_anr_invalid_aggregates(self):
  321. default_request = {
  322. "project": [-1],
  323. "statsPeriod": "1d",
  324. "interval": "1d",
  325. "field": ["anr_rate()", "crash_free_rate(user)"],
  326. }
  327. def req(**kwargs):
  328. return self.do_request(dict(default_request, **kwargs))
  329. response = req()
  330. assert response.status_code == 200
  331. # Both these fields are supported by the metrics backend
  332. assert response.data["groups"] == [
  333. {
  334. "by": {},
  335. "totals": {"anr_rate()": 0.0, "crash_free_rate(user)": 1.0},
  336. "series": {"anr_rate()": [None, 0.0], "crash_free_rate(user)": [None, 1.0]},
  337. }
  338. ]
  339. response = req(field=["anr_rate()", "sum(session)"])
  340. assert response.status_code == 200
  341. # Both these fields are supported by the metrics backend
  342. assert response.data["groups"] == [
  343. {
  344. "by": {},
  345. "totals": {"anr_rate()": 0.0, "sum(session)": 9},
  346. "series": {"anr_rate()": [None, 0.0], "sum(session)": [0, 9]},
  347. }
  348. ]
  349. @freeze_time(MOCK_DATETIME)
  350. def test_filter_environment(self):
  351. response = self.do_request(
  352. {
  353. "project": [-1],
  354. "statsPeriod": "1d",
  355. "interval": "1d",
  356. "field": ["sum(session)"],
  357. "query": "environment:development",
  358. }
  359. )
  360. assert response.status_code == 200, response.content
  361. assert result_sorted(response.data)["groups"] == [
  362. {"by": {}, "series": {"sum(session)": [0, 1]}, "totals": {"sum(session)": 1}}
  363. ]
  364. response = self.do_request(
  365. {
  366. "project": [-1],
  367. "statsPeriod": "1d",
  368. "interval": "1d",
  369. "field": ["sum(session)"],
  370. "environment": ["development"],
  371. }
  372. )
  373. assert response.status_code == 200, response.content
  374. assert result_sorted(response.data)["groups"] == [
  375. {"by": {}, "series": {"sum(session)": [0, 1]}, "totals": {"sum(session)": 1}}
  376. ]
  377. @freeze_time(MOCK_DATETIME)
  378. def test_filter_release(self):
  379. response = self.do_request(
  380. {
  381. "project": [-1],
  382. "statsPeriod": "1d",
  383. "interval": "1d",
  384. "field": ["sum(session)"],
  385. "query": "release:foo@1.1.0",
  386. }
  387. )
  388. assert response.status_code == 200, response.content
  389. assert result_sorted(response.data)["groups"] == [
  390. {"by": {}, "series": {"sum(session)": [0, 1]}, "totals": {"sum(session)": 1}}
  391. ]
  392. response = self.do_request(
  393. {
  394. "project": [-1],
  395. "statsPeriod": "1d",
  396. "interval": "1d",
  397. "field": ["sum(session)"],
  398. "query": 'release:"foo@1.1.0" or release:"foo@1.2.0"',
  399. }
  400. )
  401. assert response.status_code == 200, response.content
  402. assert result_sorted(response.data)["groups"] == [
  403. {"by": {}, "series": {"sum(session)": [0, 2]}, "totals": {"sum(session)": 2}}
  404. ]
  405. response = self.do_request(
  406. {
  407. "project": [-1],
  408. "statsPeriod": "1d",
  409. "interval": "1d",
  410. "field": ["sum(session)"],
  411. "query": 'release:"foo@1.1.0" or release:["foo@1.2.0", release:"foo@1.3.0"]',
  412. "groupBy": ["release"],
  413. }
  414. )
  415. assert response.status_code == 200, response.content
  416. assert result_sorted(response.data)["groups"] == [
  417. {
  418. "by": {"release": "foo@1.1.0"},
  419. "series": {"sum(session)": [0, 1]},
  420. "totals": {"sum(session)": 1},
  421. },
  422. {
  423. "by": {"release": "foo@1.2.0"},
  424. "series": {"sum(session)": [0, 1]},
  425. "totals": {"sum(session)": 1},
  426. },
  427. ]
  428. @freeze_time(MOCK_DATETIME)
  429. def test_filter_unknown_release(self):
  430. response = self.do_request(
  431. {
  432. "project": [-1],
  433. "statsPeriod": "1d",
  434. "interval": "1h",
  435. "field": ["sum(session)"],
  436. "query": "release:foo@6.6.6",
  437. "groupBy": "session.status",
  438. }
  439. )
  440. assert response.status_code == 200, response.content
  441. @freeze_time(MOCK_DATETIME)
  442. def test_filter_unknown_release_in(self):
  443. response = self.do_request(
  444. {
  445. "project": [-1],
  446. "statsPeriod": "1d",
  447. "interval": "1d",
  448. "field": ["sum(session)"],
  449. "query": "release:[foo@6.6.6]",
  450. "groupBy": "session.status",
  451. }
  452. )
  453. assert response.status_code == 200, response.content
  454. assert result_sorted(response.data)["groups"] == [
  455. {
  456. "by": {"session.status": status},
  457. "series": {"sum(session)": [0, 0]},
  458. "totals": {"sum(session)": 0},
  459. }
  460. for status in ("abnormal", "crashed", "errored", "healthy")
  461. ]
  462. @freeze_time(MOCK_DATETIME)
  463. def test_groupby_project(self):
  464. response = self.do_request(
  465. {
  466. "project": [-1],
  467. "statsPeriod": "1d",
  468. "interval": "1d",
  469. "field": ["sum(session)"],
  470. "groupBy": ["project"],
  471. }
  472. )
  473. assert response.status_code == 200, response.content
  474. assert result_sorted(response.data)["groups"] == [
  475. {
  476. "by": {"project": self.project1.id},
  477. "series": {"sum(session)": [0, 4]},
  478. "totals": {"sum(session)": 4},
  479. },
  480. {
  481. "by": {"project": self.project2.id},
  482. "series": {"sum(session)": [0, 2]},
  483. "totals": {"sum(session)": 2},
  484. },
  485. {
  486. "by": {"project": self.project3.id},
  487. "series": {"sum(session)": [0, 3]},
  488. "totals": {"sum(session)": 3},
  489. },
  490. ]
  491. @freeze_time(MOCK_DATETIME)
  492. def test_groupby_environment(self):
  493. response = self.do_request(
  494. {
  495. "project": [-1],
  496. "statsPeriod": "1d",
  497. "interval": "1d",
  498. "field": ["sum(session)"],
  499. "groupBy": ["environment"],
  500. }
  501. )
  502. assert response.status_code == 200, response.content
  503. assert result_sorted(response.data)["groups"] == [
  504. {
  505. "by": {"environment": "development"},
  506. "series": {"sum(session)": [0, 1]},
  507. "totals": {"sum(session)": 1},
  508. },
  509. {
  510. "by": {"environment": "production"},
  511. "series": {"sum(session)": [0, 8]},
  512. "totals": {"sum(session)": 8},
  513. },
  514. ]
  515. @freeze_time(MOCK_DATETIME)
  516. def test_groupby_release(self):
  517. response = self.do_request(
  518. {
  519. "project": [-1],
  520. "statsPeriod": "1d",
  521. "interval": "1d",
  522. "field": ["sum(session)"],
  523. "groupBy": ["release"],
  524. }
  525. )
  526. assert response.status_code == 200, response.content
  527. assert result_sorted(response.data)["groups"] == [
  528. {
  529. "by": {"release": "foo@1.0.0"},
  530. "series": {"sum(session)": [0, 7]},
  531. "totals": {"sum(session)": 7},
  532. },
  533. {
  534. "by": {"release": "foo@1.1.0"},
  535. "series": {"sum(session)": [0, 1]},
  536. "totals": {"sum(session)": 1},
  537. },
  538. {
  539. "by": {"release": "foo@1.2.0"},
  540. "series": {"sum(session)": [0, 1]},
  541. "totals": {"sum(session)": 1},
  542. },
  543. ]
  544. @freeze_time(MOCK_DATETIME)
  545. def test_groupby_status(self):
  546. response = self.do_request(
  547. {
  548. "project": [-1],
  549. "statsPeriod": "1d",
  550. "interval": "1d",
  551. "field": ["sum(session)"],
  552. "groupBy": ["session.status"],
  553. }
  554. )
  555. assert response.status_code == 200, response.content
  556. assert result_sorted(response.data)["groups"] == [
  557. {
  558. "by": {"session.status": "abnormal"},
  559. "series": {"sum(session)": [0, 0]},
  560. "totals": {"sum(session)": 0},
  561. },
  562. {
  563. "by": {"session.status": "crashed"},
  564. "series": {"sum(session)": [0, 1]},
  565. "totals": {"sum(session)": 1},
  566. },
  567. {
  568. "by": {"session.status": "errored"},
  569. "series": {"sum(session)": [0, 2]},
  570. "totals": {"sum(session)": 2},
  571. },
  572. {
  573. "by": {"session.status": "healthy"},
  574. "series": {"sum(session)": [0, 6]},
  575. "totals": {"sum(session)": 6},
  576. },
  577. ]
  578. @freeze_time(MOCK_DATETIME)
  579. def test_groupby_cross(self):
  580. response = self.do_request(
  581. {
  582. "project": [-1],
  583. "statsPeriod": "1d",
  584. "interval": "1d",
  585. "field": ["sum(session)"],
  586. "groupBy": ["release", "environment"],
  587. }
  588. )
  589. assert response.status_code == 200, response.content
  590. assert result_sorted(response.data)["groups"] == [
  591. {
  592. "by": {"environment": "development", "release": "foo@1.0.0"},
  593. "series": {"sum(session)": [0, 1]},
  594. "totals": {"sum(session)": 1},
  595. },
  596. {
  597. "by": {"environment": "production", "release": "foo@1.0.0"},
  598. "series": {"sum(session)": [0, 6]},
  599. "totals": {"sum(session)": 6},
  600. },
  601. {
  602. "by": {"environment": "production", "release": "foo@1.1.0"},
  603. "series": {"sum(session)": [0, 1]},
  604. "totals": {"sum(session)": 1},
  605. },
  606. {
  607. "by": {"environment": "production", "release": "foo@1.2.0"},
  608. "series": {"sum(session)": [0, 1]},
  609. "totals": {"sum(session)": 1},
  610. },
  611. ]
  612. @freeze_time(MOCK_DATETIME)
  613. def test_users_groupby(self):
  614. response = self.do_request(
  615. {
  616. "project": [-1],
  617. "statsPeriod": "1d",
  618. "interval": "1d",
  619. "field": ["count_unique(user)"],
  620. }
  621. )
  622. assert response.status_code == 200, response.content
  623. assert result_sorted(response.data)["groups"] == [
  624. {
  625. "by": {},
  626. "series": {"count_unique(user)": [0, 1]},
  627. "totals": {"count_unique(user)": 1},
  628. }
  629. ]
  630. response = self.do_request(
  631. {
  632. "project": [-1],
  633. "statsPeriod": "1d",
  634. "interval": "1d",
  635. "field": ["count_unique(user)"],
  636. "groupBy": ["session.status"],
  637. }
  638. )
  639. assert response.status_code == 200, response.content
  640. assert result_sorted(response.data)["groups"] == [
  641. {
  642. "by": {"session.status": "abnormal"},
  643. "series": {"count_unique(user)": [0, 0]},
  644. "totals": {"count_unique(user)": 0},
  645. },
  646. {
  647. "by": {"session.status": "crashed"},
  648. "series": {"count_unique(user)": [0, 0]},
  649. "totals": {"count_unique(user)": 0},
  650. },
  651. {
  652. "by": {"session.status": "errored"},
  653. "series": {"count_unique(user)": [0, 1]},
  654. "totals": {"count_unique(user)": 1},
  655. },
  656. {
  657. "by": {"session.status": "healthy"},
  658. "series": {"count_unique(user)": [0, 0]},
  659. "totals": {"count_unique(user)": 0},
  660. },
  661. ]
  662. expected_duration_values = {
  663. "avg(session.duration)": 42375.0,
  664. "max(session.duration)": 80000.0,
  665. "p50(session.duration)": 33500.0,
  666. "p75(session.duration)": 53750.0,
  667. "p90(session.duration)": 71600.0,
  668. "p95(session.duration)": 75800.0,
  669. "p99(session.duration)": 79159.99999999999,
  670. }
  671. @freeze_time(MOCK_DATETIME)
  672. def test_users_groupby_status_advanced(self):
  673. project = self.create_project()
  674. user1 = uuid4().hex
  675. session1 = uuid4().hex
  676. user2 = uuid4().hex
  677. session2a = uuid4().hex
  678. session2b = uuid4().hex
  679. user3 = uuid4().hex
  680. session3 = uuid4().hex
  681. self.store_session(
  682. make_session(project, session_id=session1, distinct_id=user1, status="ok")
  683. )
  684. self.store_session(
  685. make_session(
  686. project, session_id=session1, distinct_id=user1, seq=1, errors=1, status="errored"
  687. )
  688. )
  689. self.store_session(
  690. make_session(project, session_id=session1, distinct_id=user1, seq=2, status="crashed")
  691. )
  692. self.store_session(
  693. make_session(project, session_id=session2a, distinct_id=user2, status="ok")
  694. )
  695. self.store_session(
  696. make_session(project, session_id=session2b, distinct_id=user2, status="ok")
  697. )
  698. self.store_session(
  699. make_session(project, session_id=session2b, distinct_id=user2, status="abnormal")
  700. )
  701. self.store_session(
  702. make_session(
  703. project, session_id=session3, distinct_id=user3, errors=123, status="errored"
  704. )
  705. )
  706. # Add some extra healthy users:
  707. for _ in range(3):
  708. user = uuid4().hex
  709. self.store_session(make_session(project, distinct_id=user))
  710. # First, check if totals make sense:
  711. response = self.do_request(
  712. {
  713. "project": [project.id],
  714. "statsPeriod": "1d",
  715. "interval": "1d",
  716. "field": ["count_unique(user)"],
  717. }
  718. )
  719. assert response.status_code == 200, response.content
  720. assert result_sorted(response.data)["groups"] == [
  721. {
  722. "by": {},
  723. "series": {"count_unique(user)": [0, 6]},
  724. "totals": {"count_unique(user)": 6},
  725. },
  726. ]
  727. # Then check if grouping makes sense:
  728. response = self.do_request(
  729. {
  730. "project": [project.id],
  731. "statsPeriod": "1d",
  732. "interval": "1d",
  733. "field": ["count_unique(user)"],
  734. "groupBy": ["session.status"],
  735. }
  736. )
  737. assert response.status_code == 200, response.content
  738. assert result_sorted(response.data)["groups"] == [
  739. {
  740. "by": {"session.status": "abnormal"},
  741. "series": {"count_unique(user)": [0, 1]},
  742. "totals": {"count_unique(user)": 1},
  743. },
  744. {
  745. "by": {"session.status": "crashed"},
  746. "series": {"count_unique(user)": [0, 1]},
  747. "totals": {"count_unique(user)": 1},
  748. },
  749. {
  750. "by": {"session.status": "errored"},
  751. "series": {"count_unique(user)": [0, 1]},
  752. "totals": {"count_unique(user)": 1},
  753. },
  754. {
  755. # user
  756. "by": {"session.status": "healthy"},
  757. "series": {"count_unique(user)": [0, 3]},
  758. "totals": {"count_unique(user)": 3},
  759. },
  760. ]
  761. @freeze_time(MOCK_DATETIME)
  762. def test_duration_percentiles(self):
  763. response = self.do_request(
  764. {
  765. "project": [-1],
  766. "statsPeriod": "1d",
  767. "interval": "1d",
  768. "field": [
  769. "avg(session.duration)",
  770. "p50(session.duration)",
  771. "p75(session.duration)",
  772. "p90(session.duration)",
  773. "p95(session.duration)",
  774. "p99(session.duration)",
  775. "max(session.duration)",
  776. ],
  777. }
  778. )
  779. assert response.status_code == 200, response.content
  780. expected = self.expected_duration_values
  781. groups = result_sorted(response.data)["groups"]
  782. assert len(groups) == 1, groups
  783. group = groups[0]
  784. assert group["by"] == {}
  785. assert group["totals"] == pytest.approx(expected)
  786. for key, series in group["series"].items():
  787. assert series == pytest.approx([None, expected[key]])
  788. @freeze_time(MOCK_DATETIME)
  789. def test_duration_percentiles_groupby(self):
  790. response = self.do_request(
  791. {
  792. "project": [-1],
  793. "statsPeriod": "1d",
  794. "interval": "1d",
  795. "field": [
  796. "avg(session.duration)",
  797. "p50(session.duration)",
  798. "p75(session.duration)",
  799. "p90(session.duration)",
  800. "p95(session.duration)",
  801. "p99(session.duration)",
  802. "max(session.duration)",
  803. ],
  804. "groupBy": "session.status",
  805. }
  806. )
  807. assert response.status_code == 200, response.content
  808. expected = self.expected_duration_values
  809. seen = set() # Make sure all session statuses are listed
  810. for group in result_sorted(response.data)["groups"]:
  811. seen.add(group["by"].get("session.status"))
  812. if group["by"] == {"session.status": "healthy"}:
  813. assert group["totals"] == pytest.approx(expected)
  814. for key, series in group["series"].items():
  815. assert series == pytest.approx([None, expected[key]])
  816. else:
  817. # Everything's none:
  818. assert group["totals"] == {key: None for key in expected}, group["by"]
  819. assert group["series"] == {key: [None, None] for key in expected}
  820. assert seen == {"abnormal", "crashed", "errored", "healthy"}
  821. @freeze_time(MOCK_DATETIME)
  822. def test_snuba_limit_exceeded(self):
  823. # 2 * 4 => only show two groups
  824. with (
  825. patch("sentry.snuba.sessions_v2.SNUBA_LIMIT", 8),
  826. patch("sentry.snuba.metrics.query.MAX_POINTS", 8),
  827. ):
  828. response = self.do_request(
  829. {
  830. "project": [-1],
  831. "statsPeriod": "3d",
  832. "interval": "1d",
  833. # "user" is the first field, but "session" always wins:
  834. "field": ["count_unique(user)", "sum(session)"],
  835. "groupBy": ["project", "release", "environment"],
  836. }
  837. )
  838. assert response.status_code == 200, response.content
  839. assert result_sorted(response.data)["groups"] == [
  840. {
  841. "by": {
  842. "release": "foo@1.0.0",
  843. "environment": "production",
  844. "project": self.project1.id,
  845. },
  846. "totals": {"sum(session)": 3, "count_unique(user)": 0},
  847. "series": {"sum(session)": [0, 0, 0, 3], "count_unique(user)": [0, 0, 0, 0]},
  848. },
  849. {
  850. "by": {
  851. "release": "foo@1.0.0",
  852. "environment": "production",
  853. "project": self.project3.id,
  854. },
  855. "totals": {"sum(session)": 2, "count_unique(user)": 1},
  856. "series": {"sum(session)": [0, 0, 0, 2], "count_unique(user)": [0, 0, 0, 1]},
  857. },
  858. ]
  859. @freeze_time(MOCK_DATETIME)
  860. def test_snuba_limit_exceeded_groupby_status(self):
  861. """Get consistent result when grouping by status"""
  862. # 2 * 4 => only show two groups
  863. with (
  864. patch("sentry.snuba.sessions_v2.SNUBA_LIMIT", 8),
  865. patch("sentry.snuba.metrics.query.MAX_POINTS", 8),
  866. ):
  867. response = self.do_request(
  868. {
  869. "project": [-1],
  870. "statsPeriod": "3d",
  871. "interval": "1d",
  872. "field": ["sum(session)", "count_unique(user)"],
  873. "groupBy": ["project", "release", "environment", "session.status"],
  874. }
  875. )
  876. assert response.status_code == 200, response.content
  877. assert result_sorted(response.data)["groups"] == [
  878. {
  879. "by": {
  880. "project": self.project1.id,
  881. "release": "foo@1.0.0",
  882. "session.status": "abnormal",
  883. "environment": "production",
  884. },
  885. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  886. "series": {"sum(session)": [0, 0, 0, 0], "count_unique(user)": [0, 0, 0, 0]},
  887. },
  888. {
  889. "by": {
  890. "project": self.project1.id,
  891. "release": "foo@1.0.0",
  892. "session.status": "crashed",
  893. "environment": "production",
  894. },
  895. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  896. "series": {"sum(session)": [0, 0, 0, 0], "count_unique(user)": [0, 0, 0, 0]},
  897. },
  898. {
  899. "by": {
  900. "project": self.project1.id,
  901. "release": "foo@1.0.0",
  902. "environment": "production",
  903. "session.status": "errored",
  904. },
  905. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  906. "series": {"sum(session)": [0, 0, 0, 0], "count_unique(user)": [0, 0, 0, 0]},
  907. },
  908. {
  909. "by": {
  910. "project": self.project1.id,
  911. "session.status": "healthy",
  912. "release": "foo@1.0.0",
  913. "environment": "production",
  914. },
  915. "totals": {"sum(session)": 3, "count_unique(user)": 0},
  916. "series": {"sum(session)": [0, 0, 0, 3], "count_unique(user)": [0, 0, 0, 0]},
  917. },
  918. {
  919. "by": {
  920. "session.status": "abnormal",
  921. "release": "foo@1.0.0",
  922. "project": self.project3.id,
  923. "environment": "production",
  924. },
  925. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  926. "series": {"sum(session)": [0, 0, 0, 0], "count_unique(user)": [0, 0, 0, 0]},
  927. },
  928. {
  929. "by": {
  930. "release": "foo@1.0.0",
  931. "project": self.project3.id,
  932. "session.status": "crashed",
  933. "environment": "production",
  934. },
  935. "totals": {"sum(session)": 0, "count_unique(user)": 0},
  936. "series": {"sum(session)": [0, 0, 0, 0], "count_unique(user)": [0, 0, 0, 0]},
  937. },
  938. {
  939. "by": {
  940. "release": "foo@1.0.0",
  941. "project": self.project3.id,
  942. "environment": "production",
  943. "session.status": "errored",
  944. },
  945. "totals": {"sum(session)": 1, "count_unique(user)": 1},
  946. "series": {"sum(session)": [0, 0, 0, 1], "count_unique(user)": [0, 0, 0, 1]},
  947. },
  948. {
  949. "by": {
  950. "session.status": "healthy",
  951. "release": "foo@1.0.0",
  952. "project": self.project3.id,
  953. "environment": "production",
  954. },
  955. "totals": {"sum(session)": 1, "count_unique(user)": 0},
  956. "series": {"sum(session)": [0, 0, 0, 1], "count_unique(user)": [0, 0, 0, 0]},
  957. },
  958. ]
  959. @freeze_time(MOCK_DATETIME)
  960. def test_environment_filter_not_present_in_query(self):
  961. self.create_environment(name="abc")
  962. response = self.do_request(
  963. {
  964. "project": [-1],
  965. "statsPeriod": "1d",
  966. "interval": "1d",
  967. "field": ["sum(session)"],
  968. "environment": ["development", "abc"],
  969. }
  970. )
  971. assert response.status_code == 200, response.content
  972. assert result_sorted(response.data)["groups"] == [
  973. {"by": {}, "series": {"sum(session)": [0, 1]}, "totals": {"sum(session)": 1}}
  974. ]
  975. @freeze_time(MOCK_DATETIME)
  976. def test_sessions_without_users(self):
  977. # The first field defines by which groups additional queries are filtered
  978. # But if the first field is the user count, the series should still
  979. # contain the session counts even if the project does not track users
  980. response = self.do_request(
  981. {
  982. "project": self.project.id, # project without users
  983. "statsPeriod": "1d",
  984. "interval": "1d",
  985. "field": ["count_unique(user)", "sum(session)"],
  986. "groupBy": "release",
  987. }
  988. )
  989. assert response.status_code == 200, response.content
  990. assert result_sorted(response.data)["groups"] == [
  991. {
  992. "by": {"release": "foo@1.0.0"},
  993. "series": {"count_unique(user)": [0, 0], "sum(session)": [0, 3]},
  994. "totals": {"count_unique(user)": 0, "sum(session)": 3},
  995. },
  996. {
  997. "by": {"release": "foo@1.1.0"},
  998. "series": {"count_unique(user)": [0, 0], "sum(session)": [0, 1]},
  999. "totals": {"count_unique(user)": 0, "sum(session)": 1},
  1000. },
  1001. ]
  1002. @freeze_time(MOCK_DATETIME + datetime.timedelta(days=2))
  1003. def test_groupby_no_data(self):
  1004. # Empty results for everything
  1005. response = self.do_request(
  1006. {
  1007. "project": self.project.id, # project without users
  1008. "statsPeriod": "1d",
  1009. "interval": "1d",
  1010. "field": ["count_unique(user)", "sum(session)"],
  1011. "groupBy": "release",
  1012. }
  1013. )
  1014. assert response.status_code == 200, response.content
  1015. assert result_sorted(response.data)["groups"] == []
  1016. @freeze_time(MOCK_DATETIME)
  1017. def test_mix_known_and_unknown_strings(self):
  1018. response = self.do_request(
  1019. {
  1020. "project": self.project.id, # project without users
  1021. "statsPeriod": "1d",
  1022. "interval": "1d",
  1023. "field": ["count_unique(user)", "sum(session)"],
  1024. "query": "environment:[production,foo]",
  1025. }
  1026. )
  1027. assert response.status_code == 200, response.data
  1028. @freeze_time(MOCK_DATETIME)
  1029. def test_release_semver_filter(self):
  1030. r1 = self.create_release(version="ahmed@1.0.0")
  1031. r2 = self.create_release(version="ahmed@1.1.0")
  1032. r3 = self.create_release(version="ahmed@2.0.0")
  1033. for r in (r1, r2, r3):
  1034. self.store_session(make_session(self.project, release=r.version))
  1035. response = self.do_request(
  1036. {
  1037. "project": self.project.id,
  1038. "statsPeriod": "1d",
  1039. "interval": "1d",
  1040. "field": ["sum(session)"],
  1041. "groupBy": ["release"],
  1042. "query": "release.version:1.*",
  1043. }
  1044. )
  1045. assert response.status_code == 200
  1046. assert sorted(response.data["groups"], key=lambda x: x["by"]["release"]) == [
  1047. {
  1048. "by": {"release": "ahmed@1.0.0"},
  1049. "totals": {"sum(session)": 1},
  1050. "series": {"sum(session)": [0, 1]},
  1051. },
  1052. {
  1053. "by": {"release": "ahmed@1.1.0"},
  1054. "totals": {"sum(session)": 1},
  1055. "series": {"sum(session)": [0, 1]},
  1056. },
  1057. ]
  1058. @freeze_time(MOCK_DATETIME)
  1059. def test_release_package_filter(self):
  1060. r1 = self.create_release(version="ahmed@1.2.4+124")
  1061. r2 = self.create_release(version="ahmed2@1.2.5+125")
  1062. r3 = self.create_release(version="ahmed2@1.2.6+126")
  1063. for r in (r1, r2, r3):
  1064. self.store_session(make_session(self.project, release=r.version))
  1065. response = self.do_request(
  1066. {
  1067. "project": self.project.id,
  1068. "statsPeriod": "1d",
  1069. "interval": "1d",
  1070. "field": ["sum(session)"],
  1071. "groupBy": ["release"],
  1072. "query": "release.package:ahmed2",
  1073. }
  1074. )
  1075. assert response.status_code == 200
  1076. assert sorted(response.data["groups"], key=lambda x: x["by"]["release"]) == [
  1077. {
  1078. "by": {"release": "ahmed2@1.2.5+125"},
  1079. "totals": {"sum(session)": 1},
  1080. "series": {"sum(session)": [0, 1]},
  1081. },
  1082. {
  1083. "by": {"release": "ahmed2@1.2.6+126"},
  1084. "totals": {"sum(session)": 1},
  1085. "series": {"sum(session)": [0, 1]},
  1086. },
  1087. ]
  1088. @freeze_time(MOCK_DATETIME)
  1089. def test_release_build_filter(self):
  1090. r1 = self.create_release(version="ahmed@1.2.4+124")
  1091. r2 = self.create_release(version="ahmed@1.2.3+123")
  1092. r3 = self.create_release(version="ahmed2@1.2.5+125")
  1093. for r in (r1, r2, r3):
  1094. self.store_session(make_session(self.project, release=r.version))
  1095. response = self.do_request(
  1096. {
  1097. "project": self.project.id,
  1098. "statsPeriod": "1d",
  1099. "interval": "1d",
  1100. "field": ["sum(session)"],
  1101. "groupBy": ["release"],
  1102. "query": "release.build:<125",
  1103. }
  1104. )
  1105. assert response.status_code == 200
  1106. assert sorted(response.data["groups"], key=lambda x: x["by"]["release"]) == [
  1107. {
  1108. "by": {"release": "ahmed@1.2.3+123"},
  1109. "totals": {"sum(session)": 1},
  1110. "series": {"sum(session)": [0, 1]},
  1111. },
  1112. {
  1113. "by": {"release": "ahmed@1.2.4+124"},
  1114. "totals": {"sum(session)": 1},
  1115. "series": {"sum(session)": [0, 1]},
  1116. },
  1117. ]
  1118. @freeze_time(MOCK_DATETIME)
  1119. def test_release_stage_filter(self):
  1120. new_env = self.create_environment(name="new_env")
  1121. adopted_release = self.create_release(version="adopted_release")
  1122. not_adopted_release = self.create_release(version="not_adopted_release")
  1123. ReleaseProjectEnvironment.objects.create(
  1124. project_id=self.project.id,
  1125. release_id=adopted_release.id,
  1126. environment_id=new_env.id,
  1127. adopted=timezone.now(),
  1128. )
  1129. ReleaseProjectEnvironment.objects.create(
  1130. project_id=self.project.id,
  1131. release_id=not_adopted_release.id,
  1132. environment_id=new_env.id,
  1133. )
  1134. for r in (adopted_release, not_adopted_release):
  1135. self.store_session(
  1136. make_session(self.project, release=r.version, environment=new_env.name)
  1137. )
  1138. response = self.do_request(
  1139. {
  1140. "project": self.project.id,
  1141. "statsPeriod": "1d",
  1142. "interval": "1d",
  1143. "field": ["sum(session)"],
  1144. "groupBy": ["release"],
  1145. "query": "release.stage:adopted",
  1146. "environment": new_env.name,
  1147. }
  1148. )
  1149. assert response.status_code == 200
  1150. assert response.data["groups"] == [
  1151. {
  1152. "by": {"release": "adopted_release"},
  1153. "totals": {"sum(session)": 1},
  1154. "series": {"sum(session)": [0, 1]},
  1155. },
  1156. ]
  1157. @freeze_time(MOCK_DATETIME)
  1158. def test_orderby(self):
  1159. response = self.do_request(
  1160. {
  1161. "project": [-1],
  1162. "statsPeriod": "2d",
  1163. "interval": "1d",
  1164. "field": ["sum(session)"],
  1165. "orderBy": "foobar",
  1166. }
  1167. )
  1168. assert response.status_code == 400
  1169. assert response.data == {"detail": "'orderBy' must be one of the provided 'fields'"}
  1170. response = self.do_request(
  1171. {
  1172. "project": [-1],
  1173. "statsPeriod": "2d",
  1174. "interval": "1d",
  1175. "field": ["sum(session)"],
  1176. "orderBy": "count_unique(user)", # wrong field
  1177. }
  1178. )
  1179. assert response.status_code == 400
  1180. assert response.data == {"detail": "'orderBy' must be one of the provided 'fields'"}
  1181. # Cannot sort by more than one field
  1182. response = self.do_request(
  1183. {
  1184. "project": [-1],
  1185. "statsPeriod": "2d",
  1186. "interval": "1d",
  1187. "field": ["sum(session)", "count_unique(user)"],
  1188. "orderBy": ["sum(session)", "count_unique(user)"],
  1189. }
  1190. )
  1191. assert response.status_code == 400
  1192. assert response.data == {"detail": "Cannot order by multiple fields"}
  1193. response = self.do_request(
  1194. {
  1195. "project": [-1],
  1196. "statsPeriod": "2d",
  1197. "interval": "1d",
  1198. "field": ["sum(session)"],
  1199. "orderBy": "sum(session)", # misses group by, but why not
  1200. }
  1201. )
  1202. assert response.status_code == 200
  1203. response = self.do_request(
  1204. {
  1205. "project": [-1],
  1206. "statsPeriod": "2d",
  1207. "interval": "1d",
  1208. "field": ["sum(session)"],
  1209. "orderBy": "sum(session)",
  1210. "groupBy": ["session.status"],
  1211. }
  1212. )
  1213. assert response.status_code == 400
  1214. assert response.data == {"detail": "Cannot use 'orderBy' when grouping by sessions.status"}
  1215. response = self.do_request(
  1216. {
  1217. "project": [self.project.id, self.project3.id],
  1218. "statsPeriod": "2d",
  1219. "interval": "1d",
  1220. "field": ["sum(session)", "p95(session.duration)"],
  1221. "orderBy": "p95(session.duration)",
  1222. "groupBy": ["project", "release", "environment"],
  1223. }
  1224. )
  1225. expected_groups = [
  1226. {
  1227. "by": {
  1228. "project": self.project.id,
  1229. "release": "foo@1.0.0",
  1230. "environment": "production",
  1231. },
  1232. "totals": {"sum(session)": 3, "p95(session.duration)": 25000.0},
  1233. "series": {
  1234. "sum(session)": [0, 0, 3],
  1235. "p95(session.duration)": [None, None, 25000.0],
  1236. },
  1237. },
  1238. {
  1239. "by": {
  1240. "project": self.project3.id,
  1241. "release": "foo@1.2.0",
  1242. "environment": "production",
  1243. },
  1244. "totals": {"sum(session)": 1, "p95(session.duration)": 37000.0},
  1245. "series": {
  1246. "sum(session)": [0, 0, 1],
  1247. "p95(session.duration)": [None, None, 37000.0],
  1248. },
  1249. },
  1250. {
  1251. "by": {
  1252. "project": self.project.id,
  1253. "release": "foo@1.1.0",
  1254. "environment": "production",
  1255. },
  1256. "totals": {"sum(session)": 1, "p95(session.duration)": 49000.0},
  1257. "series": {
  1258. "sum(session)": [0, 0, 1],
  1259. "p95(session.duration)": [None, None, 49000.0],
  1260. },
  1261. },
  1262. {
  1263. "by": {
  1264. "project": self.project3.id,
  1265. "release": "foo@1.0.0",
  1266. "environment": "production",
  1267. },
  1268. "totals": {"sum(session)": 2, "p95(session.duration)": 79400.0},
  1269. "series": {
  1270. "sum(session)": [0, 0, 2],
  1271. "p95(session.duration)": [None, None, 79400.0],
  1272. },
  1273. },
  1274. ]
  1275. # Not using `result_sorted` here, because we want to verify the order
  1276. assert response.status_code == 200, response.data
  1277. assert response.data["groups"] == expected_groups
  1278. # Sort descending
  1279. response = self.do_request(
  1280. {
  1281. "project": [self.project.id, self.project3.id],
  1282. "statsPeriod": "2d",
  1283. "interval": "1d",
  1284. "field": ["sum(session)", "p95(session.duration)"],
  1285. "orderBy": "-p95(session.duration)",
  1286. "groupBy": ["project", "release", "environment"],
  1287. }
  1288. )
  1289. assert response.status_code == 200
  1290. assert response.data["groups"] == list(reversed(expected_groups))
  1291. # Add some more code coverage
  1292. all_fields = [
  1293. "sum(session)",
  1294. "count_unique(user)",
  1295. "avg(session.duration)",
  1296. ]
  1297. for field in all_fields:
  1298. assert (
  1299. self.do_request(
  1300. {
  1301. "project": [self.project.id, self.project3.id],
  1302. "statsPeriod": "2d",
  1303. "interval": "1d",
  1304. "field": all_fields,
  1305. "orderBy": field,
  1306. "groupBy": ["project", "release", "environment"],
  1307. }
  1308. ).status_code
  1309. == 200
  1310. )
  1311. @freeze_time(MOCK_DATETIME)
  1312. def test_wildcard_search(self):
  1313. default_request = {
  1314. "project": [-1],
  1315. "statsPeriod": "2d",
  1316. "interval": "1d",
  1317. }
  1318. def req(**kwargs):
  1319. return self.do_request(dict(default_request, **kwargs))
  1320. response = req(field=["sum(session)"], query="release:foo@*")
  1321. assert response.status_code == 400
  1322. assert response.data == {"detail": "Invalid condition: wildcard search is not supported"}
  1323. response = req(field=["sum(session)"], query="release:foo@* AND release:bar@*")
  1324. assert response.status_code == 400
  1325. assert response.data == {"detail": "Invalid condition: wildcard search is not supported"}
  1326. response = req(field=["sum(session)"], query="release:foo@* OR release:bar@*")
  1327. assert response.status_code == 400
  1328. assert response.data == {"detail": "Invalid condition: wildcard search is not supported"}
  1329. response = req(field=["sum(session)"], query="(release:foo@* OR release:bar) OR project:1")
  1330. assert response.status_code == 400
  1331. assert response.data == {"detail": "Invalid condition: wildcard search is not supported"}
  1332. @freeze_time(MOCK_DATETIME)
  1333. def test_filter_by_session_status(self):
  1334. default_request = {
  1335. "project": [-1],
  1336. "statsPeriod": "1d",
  1337. "interval": "1d",
  1338. }
  1339. def req(**kwargs):
  1340. return self.do_request(dict(default_request, **kwargs))
  1341. response = req(field=["sum(session)"], query="session.status:bogus")
  1342. assert response.status_code == 200, response.content
  1343. assert result_sorted(response.data)["groups"] == []
  1344. response = req(field=["sum(session)"], query="!session.status:healthy")
  1345. assert response.status_code == 200, response.content
  1346. assert result_sorted(response.data)["groups"] == [
  1347. {"by": {}, "series": {"sum(session)": [0, 3]}, "totals": {"sum(session)": 3}}
  1348. ]
  1349. # sum(session) filtered by multiple statuses adds them
  1350. response = req(field=["sum(session)"], query="session.status:[healthy, errored]")
  1351. assert response.status_code == 200, response.content
  1352. assert result_sorted(response.data)["groups"] == [
  1353. {"by": {}, "series": {"sum(session)": [0, 8]}, "totals": {"sum(session)": 8}}
  1354. ]
  1355. response = req(
  1356. field=["sum(session)"],
  1357. query="session.status:[healthy, errored]",
  1358. groupBy="session.status",
  1359. )
  1360. assert response.status_code == 200, response.content
  1361. assert result_sorted(response.data)["groups"] == [
  1362. {
  1363. "by": {"session.status": "errored"},
  1364. "totals": {"sum(session)": 2},
  1365. "series": {"sum(session)": [0, 2]},
  1366. },
  1367. {
  1368. "by": {"session.status": "healthy"},
  1369. "totals": {"sum(session)": 6},
  1370. "series": {"sum(session)": [0, 6]},
  1371. },
  1372. ]
  1373. response = req(field=["sum(session)"], query="session.status:healthy release:foo@1.1.0")
  1374. assert response.status_code == 200, response.content
  1375. assert result_sorted(response.data)["groups"] == [
  1376. {"by": {}, "series": {"sum(session)": [0, 1]}, "totals": {"sum(session)": 1}}
  1377. ]
  1378. response = req(field=["sum(session)"], query="session.status:healthy OR release:foo@1.1.0")
  1379. assert response.status_code == 400, response.data
  1380. assert response.data == {"detail": "Unable to parse condition with session.status"}
  1381. # count_unique(user) does not work with multiple session statuses selected
  1382. response = req(field=["count_unique(user)"], query="session.status:[healthy, errored]")
  1383. assert response.status_code == 400, response.data
  1384. assert response.data == {
  1385. "detail": "Cannot filter count_unique by multiple session.status unless it is in groupBy"
  1386. }
  1387. response = req(field=["p95(session.duration)"], query="session.status:abnormal")
  1388. assert response.status_code == 200, response.content
  1389. assert result_sorted(response.data)["groups"] == []
  1390. @freeze_time(MOCK_DATETIME)
  1391. def test_filter_by_session_status_with_groupby(self):
  1392. default_request = {
  1393. "project": [-1],
  1394. "statsPeriod": "1d",
  1395. "interval": "1d",
  1396. "groupBy": "release",
  1397. }
  1398. def req(**kwargs):
  1399. return self.do_request(dict(default_request, **kwargs))
  1400. response = req(field=["sum(session)"], query="session.status:healthy")
  1401. assert response.status_code == 200, response.content
  1402. assert result_sorted(response.data)["groups"] == [
  1403. {
  1404. "by": {"release": "foo@1.0.0"},
  1405. "series": {"sum(session)": [0, 5]},
  1406. "totals": {"sum(session)": 5},
  1407. },
  1408. {
  1409. "by": {"release": "foo@1.1.0"},
  1410. "series": {"sum(session)": [0, 1]},
  1411. "totals": {"sum(session)": 1},
  1412. },
  1413. {
  1414. "by": {"release": "foo@1.2.0"},
  1415. "series": {"sum(session)": [0, 0]},
  1416. "totals": {"sum(session)": 0},
  1417. },
  1418. ]
  1419. @freeze_time(MOCK_DATETIME)
  1420. def test_filter_by_session_status_with_orderby(self):
  1421. default_request = {
  1422. "project": [-1],
  1423. "statsPeriod": "1d",
  1424. "interval": "1d",
  1425. }
  1426. def req(**kwargs):
  1427. return self.do_request(dict(default_request, **kwargs))
  1428. response = req(
  1429. field=["sum(session)"],
  1430. query="session.status:[abnormal,crashed]",
  1431. groupBy="release",
  1432. orderBy="sum(session)",
  1433. )
  1434. assert response.status_code == 400, response.content
  1435. assert response.data == {"detail": "Cannot order by sum(session) with the current filters"}
  1436. response = req(
  1437. field=["sum(session)"],
  1438. query="session.status:healthy",
  1439. groupBy="release",
  1440. orderBy="sum(session)",
  1441. )
  1442. assert response.status_code == 400, response.content
  1443. assert response.data == {"detail": "Cannot order by sum(session) with the current filters"}
  1444. @freeze_time(MOCK_DATETIME)
  1445. def test_anr_rate(self):
  1446. def store_anr_session(user_id, mechanism):
  1447. self.store_session(
  1448. make_session(
  1449. self.project2,
  1450. distinct_id=user_id,
  1451. errors=1,
  1452. status="abnormal",
  1453. abnormal_mechanism=mechanism,
  1454. )
  1455. )
  1456. self.store_session(
  1457. make_session(
  1458. self.project2,
  1459. distinct_id="610c480b-3c47-4871-8c03-05ea04595eb0",
  1460. started=SESSION_STARTED - 60 * 60,
  1461. )
  1462. )
  1463. store_anr_session("610c480b-3c47-4871-8c03-05ea04595eb0", "anr_foreground")
  1464. self.store_session(
  1465. make_session(
  1466. self.project2,
  1467. distinct_id="ac0b74a2-8ace-415a-82d2-0fdb0d81dec4",
  1468. started=SESSION_STARTED - 60 * 60,
  1469. )
  1470. )
  1471. store_anr_session("ac0b74a2-8ace-415a-82d2-0fdb0d81dec4", "anr_background")
  1472. self.store_session(
  1473. make_session(
  1474. self.project2,
  1475. distinct_id="5344c005-653b-48b7-bbaf-d362c2f268dd",
  1476. started=SESSION_STARTED - 60 * 60,
  1477. )
  1478. )
  1479. default_request = {
  1480. "project": [-1],
  1481. "statsPeriod": "1d",
  1482. "interval": "1d",
  1483. "field": ["anr_rate()"],
  1484. }
  1485. def req(**kwargs):
  1486. return self.do_request(dict(default_request, **kwargs))
  1487. # basic test case
  1488. response = req()
  1489. assert response.status_code == 200
  1490. assert response.data["groups"] == [
  1491. {"by": {}, "totals": {"anr_rate()": 0.5}, "series": {"anr_rate()": [None, 0.5]}}
  1492. ]
  1493. # group by session.status
  1494. response = req(
  1495. groupBy="session.status",
  1496. )
  1497. assert response.status_code == 400, response.content
  1498. assert response.data == {"detail": "Cannot group field anr_rate() by session.status"}
  1499. # valid group by
  1500. response = req(
  1501. field=["anr_rate()", "foreground_anr_rate()"],
  1502. groupBy=["release", "environment"],
  1503. orderBy=["anr_rate()"],
  1504. query="release:foo@1.0.0",
  1505. )
  1506. assert response.status_code == 200, response.content
  1507. assert response.data["groups"] == [
  1508. {
  1509. "by": {"environment": "production", "release": "foo@1.0.0"},
  1510. "series": {
  1511. "anr_rate()": [None, 0.5],
  1512. "foreground_anr_rate()": [None, 0.25],
  1513. },
  1514. "totals": {
  1515. "anr_rate()": 0.5,
  1516. "foreground_anr_rate()": 0.25,
  1517. },
  1518. },
  1519. ]
  1520. @freeze_time(MOCK_DATETIME)
  1521. def test_crash_rate(self):
  1522. default_request = {
  1523. "project": [-1],
  1524. "statsPeriod": "1d",
  1525. "interval": "1d",
  1526. "field": ["crash_rate(session)"],
  1527. }
  1528. def req(**kwargs):
  1529. return self.do_request(dict(default_request, **kwargs))
  1530. # 1 - filter session.status
  1531. response = req(
  1532. query="session.status:[abnormal,crashed]",
  1533. )
  1534. assert response.status_code == 400, response.content
  1535. assert response.data == {
  1536. "detail": "Cannot filter field crash_rate(session) by session.status"
  1537. }
  1538. # 2 - group by session.status
  1539. response = req(
  1540. groupBy="session.status",
  1541. )
  1542. assert response.status_code == 400, response.content
  1543. assert response.data == {
  1544. "detail": "Cannot group field crash_rate(session) by session.status"
  1545. }
  1546. # 4 - fetch all
  1547. response = req(
  1548. field=[
  1549. "crash_rate(session)",
  1550. "crash_rate(user)",
  1551. "crash_free_rate(session)",
  1552. "crash_free_rate(user)",
  1553. ],
  1554. groupBy=["release", "environment"],
  1555. orderBy=["crash_free_rate(session)"],
  1556. query="release:foo@1.0.0",
  1557. )
  1558. assert response.status_code == 200, response.content
  1559. assert response.data["groups"] == [
  1560. {
  1561. "by": {"environment": "production", "release": "foo@1.0.0"},
  1562. "series": {
  1563. "crash_free_rate(session)": [None, 0.8333333333333334],
  1564. "crash_free_rate(user)": [None, 1.0],
  1565. "crash_rate(session)": [None, 0.16666666666666666],
  1566. "crash_rate(user)": [None, 0.0],
  1567. },
  1568. "totals": {
  1569. "crash_free_rate(session)": 0.8333333333333334,
  1570. "crash_free_rate(user)": 1.0,
  1571. "crash_rate(session)": 0.16666666666666666,
  1572. "crash_rate(user)": 0.0,
  1573. },
  1574. },
  1575. {
  1576. "by": {"environment": "development", "release": "foo@1.0.0"},
  1577. "series": {
  1578. "crash_free_rate(session)": [None, 1.0],
  1579. "crash_free_rate(user)": [None, None],
  1580. "crash_rate(session)": [None, 0.0],
  1581. "crash_rate(user)": [None, None],
  1582. },
  1583. "totals": {
  1584. "crash_free_rate(session)": 1.0,
  1585. "crash_free_rate(user)": None,
  1586. "crash_rate(session)": 0.0,
  1587. "crash_rate(user)": None,
  1588. },
  1589. },
  1590. ]
  1591. @freeze_time(MOCK_DATETIME)
  1592. def test_pagination(self):
  1593. def do_request(cursor):
  1594. return self.do_request(
  1595. {
  1596. "project": self.project.id, # project without users
  1597. "statsPeriod": "1d",
  1598. "interval": "1d",
  1599. "field": ["count_unique(user)", "sum(session)"],
  1600. "query": "",
  1601. "groupBy": "release",
  1602. "orderBy": "sum(session)",
  1603. "per_page": 1,
  1604. **({"cursor": cursor} if cursor else {}),
  1605. }
  1606. )
  1607. response = do_request(None)
  1608. assert response.status_code == 200, response.data
  1609. assert len(response.data["groups"]) == 1
  1610. assert response.data["groups"] == [
  1611. {
  1612. "by": {"release": "foo@1.1.0"},
  1613. "series": {"count_unique(user)": [0, 0], "sum(session)": [0, 1]},
  1614. "totals": {"count_unique(user)": 0, "sum(session)": 1},
  1615. }
  1616. ]
  1617. links = {link["rel"]: link for url, link in parse_link_header(response["Link"]).items()}
  1618. assert links["previous"]["results"] == "false"
  1619. assert links["next"]["results"] == "true"
  1620. response = do_request(links["next"]["cursor"])
  1621. assert response.status_code == 200, response.data
  1622. assert len(response.data["groups"]) == 1
  1623. assert response.data["groups"] == [
  1624. {
  1625. "by": {"release": "foo@1.0.0"},
  1626. "series": {"count_unique(user)": [0, 0], "sum(session)": [0, 3]},
  1627. "totals": {"count_unique(user)": 0, "sum(session)": 3},
  1628. }
  1629. ]
  1630. links = {link["rel"]: link for url, link in parse_link_header(response["Link"]).items()}
  1631. assert links["previous"]["results"] == "true"
  1632. assert links["next"]["results"] == "false"
  1633. def test_unrestricted_date_range(self):
  1634. response = self.do_request(
  1635. {
  1636. "project": [-1],
  1637. "statsPeriod": "7h",
  1638. "interval": "5m",
  1639. "field": ["sum(session)"],
  1640. }
  1641. )
  1642. assert response.status_code == 200
  1643. @freeze_time(MOCK_DATETIME)
  1644. def test_release_is_empty(self):
  1645. self.store_session(
  1646. make_session(
  1647. self.project1, started=SESSION_STARTED + 12 * 60, release="", environment=""
  1648. )
  1649. )
  1650. for query in ('release:"" environment:""', 'release:"" OR environment:""'):
  1651. # Empty strings are invalid values for releases and environments, but we should still handle those cases
  1652. # correctly at the query layer
  1653. response = self.do_request(
  1654. {
  1655. "project": self.project.id, # project without users
  1656. "statsPeriod": "1d",
  1657. "interval": "1d",
  1658. "field": ["sum(session)"],
  1659. "query": query,
  1660. "groupBy": ["release", "environment"],
  1661. }
  1662. )
  1663. assert response.status_code == 200, response.content
  1664. assert result_sorted(response.data)["groups"] == [
  1665. {
  1666. "by": {"environment": "", "release": ""},
  1667. "series": {"sum(session)": [0, 1]},
  1668. "totals": {"sum(session)": 1},
  1669. }
  1670. ]
  1671. @patch("sentry.release_health.backend", MetricsReleaseHealthBackend())
  1672. class SessionsMetricsSortReleaseTimestampTest(BaseMetricsTestCase, APITestCase):
  1673. def do_request(self, query, user=None, org=None):
  1674. self.login_as(user=user or self.user)
  1675. url = reverse(
  1676. "sentry-api-0-organization-sessions",
  1677. kwargs={"organization_id_or_slug": (org or self.organization).slug},
  1678. )
  1679. return self.client.get(url, query, format="json")
  1680. @freeze_time(MOCK_DATETIME)
  1681. def test_order_by_with_no_releases(self):
  1682. """
  1683. Test that ensures if we have no releases in the preflight query when trying to order by
  1684. `release.timestamp`, we get no groups.
  1685. Essentially testing the empty preflight query filters branch.
  1686. """
  1687. project_random = self.create_project()
  1688. for _ in range(0, 2):
  1689. self.store_session(make_session(project_random))
  1690. self.store_session(make_session(project_random, status="crashed"))
  1691. response = self.do_request(
  1692. {
  1693. "project": project_random.id,
  1694. "statsPeriod": "1d",
  1695. "interval": "1d",
  1696. "field": ["crash_free_rate(session)"],
  1697. "groupBy": ["release"],
  1698. "orderBy": "-release.timestamp",
  1699. "per_page": 3,
  1700. }
  1701. )
  1702. assert response.data["groups"] == []
  1703. def test_order_by_max_limit(self):
  1704. response = self.do_request(
  1705. {
  1706. "project": self.project.id,
  1707. "statsPeriod": "1d",
  1708. "interval": "1d",
  1709. "field": ["crash_free_rate(session)"],
  1710. "groupBy": ["release"],
  1711. "orderBy": "-release.timestamp",
  1712. "per_page": 103,
  1713. }
  1714. )
  1715. assert response.data["detail"] == (
  1716. "This limit is too high for queries that requests a preflight query. "
  1717. "Please choose a limit below 100"
  1718. )
  1719. @freeze_time(MOCK_DATETIME)
  1720. def test_order_by(self):
  1721. """
  1722. Test that ensures that we are able to get the crash_free_rate for the most 2 recent
  1723. releases when grouping by release
  1724. """
  1725. # Step 1: Create 3 releases
  1726. release1b = self.create_release(version="1B")
  1727. release1c = self.create_release(version="1C")
  1728. release1d = self.create_release(version="1D")
  1729. # Step 2: Create crash free rate for each of those releases
  1730. # Release 1c -> 66.7% Crash free rate
  1731. for _ in range(0, 2):
  1732. self.store_session(make_session(self.project, release=release1c.version))
  1733. self.store_session(make_session(self.project, release=release1c.version, status="crashed"))
  1734. # Release 1b -> 33.3% Crash free rate
  1735. for _ in range(0, 2):
  1736. self.store_session(
  1737. make_session(self.project, release=release1b.version, status="crashed")
  1738. )
  1739. self.store_session(make_session(self.project, release=release1b.version))
  1740. # Create Sessions in each of these releases
  1741. # Release 1d -> 80% Crash free rate
  1742. for _ in range(0, 4):
  1743. self.store_session(make_session(self.project, release=release1d.version))
  1744. self.store_session(make_session(self.project, release=release1d.version, status="crashed"))
  1745. # Step 3: Make request
  1746. response = self.do_request(
  1747. {
  1748. "project": self.project.id, # project without users
  1749. "statsPeriod": "1d",
  1750. "interval": "1d",
  1751. "field": ["crash_free_rate(session)"],
  1752. "groupBy": ["release"],
  1753. "orderBy": "-release.timestamp",
  1754. "per_page": 3,
  1755. }
  1756. )
  1757. # Step 4: Validate Results
  1758. assert response.data["groups"] == [
  1759. {
  1760. "by": {"release": "1D"},
  1761. "totals": {"crash_free_rate(session)": 0.8},
  1762. "series": {"crash_free_rate(session)": [None, 0.8]},
  1763. },
  1764. {
  1765. "by": {"release": "1C"},
  1766. "totals": {"crash_free_rate(session)": 0.6666666666666667},
  1767. "series": {"crash_free_rate(session)": [None, 0.6666666666666667]},
  1768. },
  1769. {
  1770. "by": {"release": "1B"},
  1771. "totals": {"crash_free_rate(session)": 0.33333333333333337},
  1772. "series": {"crash_free_rate(session)": [None, 0.33333333333333337]},
  1773. },
  1774. ]
  1775. @freeze_time(MOCK_DATETIME)
  1776. def test_order_by_with_session_status_groupby(self):
  1777. """
  1778. Test that ensures we are able to group by session.status and order by `release.timestamp`
  1779. since `release.timestamp` is generated from a preflight query
  1780. """
  1781. rando_project = self.create_project()
  1782. release_1a = self.create_release(project=rando_project, version="1A")
  1783. release_1b = self.create_release(project=rando_project, version="1B")
  1784. # Release 1B sessions
  1785. for _ in range(4):
  1786. self.store_session(
  1787. make_session(rando_project, release=release_1b.version, status="crashed")
  1788. )
  1789. for _ in range(10):
  1790. self.store_session(make_session(rando_project, release=release_1b.version))
  1791. for _ in range(3):
  1792. self.store_session(make_session(rando_project, errors=1, release=release_1b.version))
  1793. # Release 1A sessions
  1794. for _ in range(0, 2):
  1795. self.store_session(
  1796. make_session(rando_project, release=release_1a.version, status="crashed")
  1797. )
  1798. self.store_session(make_session(rando_project, release=release_1a.version))
  1799. for _ in range(3):
  1800. self.store_session(make_session(rando_project, errors=1, release=release_1a.version))
  1801. response = self.do_request(
  1802. {
  1803. "project": rando_project.id,
  1804. "statsPeriod": "1d",
  1805. "interval": "1d",
  1806. "field": ["sum(session)"],
  1807. "groupBy": ["release", "session.status"],
  1808. "orderBy": "-release.timestamp",
  1809. }
  1810. )
  1811. assert response.data["groups"] == [
  1812. {
  1813. "by": {"release": "1B", "session.status": "abnormal"},
  1814. "totals": {"sum(session)": 0},
  1815. "series": {"sum(session)": [0, 0]},
  1816. },
  1817. {
  1818. "by": {"release": "1B", "session.status": "crashed"},
  1819. "totals": {"sum(session)": 4},
  1820. "series": {"sum(session)": [0, 4]},
  1821. },
  1822. {
  1823. "by": {"release": "1B", "session.status": "errored"},
  1824. "totals": {"sum(session)": 3},
  1825. "series": {"sum(session)": [0, 3]},
  1826. },
  1827. {
  1828. "by": {"release": "1B", "session.status": "healthy"},
  1829. "totals": {"sum(session)": 10},
  1830. "series": {"sum(session)": [0, 10]},
  1831. },
  1832. {
  1833. "by": {"release": "1A", "session.status": "abnormal"},
  1834. "totals": {"sum(session)": 0},
  1835. "series": {"sum(session)": [0, 0]},
  1836. },
  1837. {
  1838. "by": {"release": "1A", "session.status": "crashed"},
  1839. "totals": {"sum(session)": 2},
  1840. "series": {"sum(session)": [0, 2]},
  1841. },
  1842. {
  1843. "by": {"release": "1A", "session.status": "errored"},
  1844. "totals": {"sum(session)": 3},
  1845. "series": {"sum(session)": [0, 3]},
  1846. },
  1847. {
  1848. "by": {"release": "1A", "session.status": "healthy"},
  1849. "totals": {"sum(session)": 1},
  1850. "series": {"sum(session)": [0, 1]},
  1851. },
  1852. ]
  1853. @freeze_time(MOCK_DATETIME)
  1854. def test_order_by_with_limit(self):
  1855. rando_project = self.create_project()
  1856. # Create two releases with no metrics data and then two releases with metric data
  1857. release_1a = self.create_release(project=rando_project, version="1A")
  1858. release_1b = self.create_release(project=rando_project, version="1B")
  1859. self.create_release(project=rando_project, version="1C")
  1860. self.create_release(project=rando_project, version="1D")
  1861. self.store_session(make_session(rando_project, release=release_1a.version))
  1862. self.store_session(make_session(rando_project, release=release_1b.version))
  1863. self.store_session(
  1864. make_session(rando_project, release=release_1b.version, status="crashed")
  1865. )
  1866. response = self.do_request(
  1867. {
  1868. "project": rando_project.id,
  1869. "statsPeriod": "1d",
  1870. "interval": "1d",
  1871. "field": ["sum(session)"],
  1872. "groupBy": ["release"],
  1873. "orderBy": "-release.timestamp",
  1874. "per_page": 3,
  1875. }
  1876. )
  1877. assert response.data["groups"] == [
  1878. {
  1879. "by": {"release": "1D"},
  1880. "totals": {"sum(session)": 0},
  1881. "series": {"sum(session)": [0, 0]},
  1882. },
  1883. {
  1884. "by": {"release": "1C"},
  1885. "totals": {"sum(session)": 0},
  1886. "series": {"sum(session)": [0, 0]},
  1887. },
  1888. {
  1889. "by": {"release": "1B"},
  1890. "totals": {"sum(session)": 2},
  1891. "series": {"sum(session)": [0, 2]},
  1892. },
  1893. ]
  1894. response = self.do_request(
  1895. {
  1896. "project": rando_project.id,
  1897. "statsPeriod": "1d",
  1898. "interval": "1d",
  1899. "field": ["sum(session)"],
  1900. "groupBy": ["release", "session.status"],
  1901. "orderBy": "-release.timestamp",
  1902. "per_page": 4,
  1903. }
  1904. )
  1905. assert response.data["groups"] == [
  1906. {
  1907. "by": {"release": "1D", "session.status": None},
  1908. "totals": {"sum(session)": 0},
  1909. "series": {"sum(session)": [0, 0]},
  1910. },
  1911. {
  1912. "by": {"release": "1C", "session.status": None},
  1913. "totals": {"sum(session)": 0},
  1914. "series": {"sum(session)": [0, 0]},
  1915. },
  1916. {
  1917. "by": {"release": "1B", "session.status": "abnormal"},
  1918. "totals": {"sum(session)": 0},
  1919. "series": {"sum(session)": [0, 0]},
  1920. },
  1921. {
  1922. "by": {"release": "1B", "session.status": "crashed"},
  1923. "totals": {"sum(session)": 1},
  1924. "series": {"sum(session)": [0, 1]},
  1925. },
  1926. ]
  1927. response = self.do_request(
  1928. {
  1929. "project": rando_project.id,
  1930. "statsPeriod": "1d",
  1931. "interval": "1d",
  1932. "field": ["sum(session)"],
  1933. "groupBy": ["release", "session.status", "project"],
  1934. "orderBy": "-release.timestamp",
  1935. "per_page": 2,
  1936. }
  1937. )
  1938. assert response.data["groups"] == [
  1939. {
  1940. "by": {"release": "1D", "session.status": None, "project": None},
  1941. "totals": {"sum(session)": 0},
  1942. "series": {"sum(session)": [0, 0]},
  1943. },
  1944. {
  1945. "by": {"release": "1C", "session.status": None, "project": None},
  1946. "totals": {"sum(session)": 0},
  1947. "series": {"sum(session)": [0, 0]},
  1948. },
  1949. ]
  1950. @freeze_time(MOCK_DATETIME)
  1951. def test_order_by_with_limit_and_offset(self):
  1952. rando_project = self.create_project()
  1953. # Create two releases with no metrics data and then two releases with metric data
  1954. release_1a = self.create_release(project=rando_project, version="1A")
  1955. release_1b = self.create_release(project=rando_project, version="1B")
  1956. self.create_release(project=rando_project, version="1C")
  1957. self.create_release(project=rando_project, version="1D")
  1958. self.store_session(make_session(rando_project, release=release_1a.version))
  1959. self.store_session(make_session(rando_project, release=release_1b.version))
  1960. response = self.do_request(
  1961. {
  1962. "project": rando_project.id,
  1963. "statsPeriod": "1d",
  1964. "interval": "1d",
  1965. "field": ["sum(session)"],
  1966. "groupBy": ["release"],
  1967. "orderBy": "-release.timestamp",
  1968. "per_page": 3,
  1969. "cursor": Cursor(0, 1),
  1970. }
  1971. )
  1972. assert response.data["detail"] == (
  1973. "Passing an offset value greater than 0 when ordering by release.timestamp "
  1974. "is not permitted"
  1975. )
  1976. @freeze_time(MOCK_DATETIME)
  1977. def test_order_by_with_environment_filter_on_preflight(self):
  1978. rando_project = self.create_project()
  1979. rando_env = self.create_environment(name="rando_env", project=self.project)
  1980. # Create two releases with no metrics data and then two releases with metric data
  1981. release_1a = self.create_release(
  1982. project=rando_project, version="1A", environments=[rando_env]
  1983. )
  1984. release_1b = self.create_release(
  1985. project=rando_project, version="1B", environments=[rando_env]
  1986. )
  1987. release_1c = self.create_release(project=rando_project, version="1C")
  1988. release_1d = self.create_release(project=rando_project, version="1D")
  1989. self.store_session(
  1990. make_session(rando_project, release=release_1a.version, environment="rando_env")
  1991. )
  1992. self.store_session(
  1993. make_session(rando_project, release=release_1b.version, environment="rando_env")
  1994. )
  1995. self.store_session(make_session(rando_project, release=release_1c.version))
  1996. self.store_session(make_session(rando_project, release=release_1d.version))
  1997. # Test env condition with IN
  1998. response = self.do_request(
  1999. {
  2000. "project": rando_project.id,
  2001. "statsPeriod": "1d",
  2002. "interval": "1d",
  2003. "field": ["sum(session)"],
  2004. "query": "environment:[rando_env,rando_enc2]",
  2005. "groupBy": ["release", "environment"],
  2006. "orderBy": "-release.timestamp",
  2007. "per_page": 4,
  2008. }
  2009. )
  2010. assert response.data["groups"] == [
  2011. {
  2012. "by": {"release": "1B", "environment": "rando_env"},
  2013. "totals": {"sum(session)": 1},
  2014. "series": {"sum(session)": [0, 1]},
  2015. },
  2016. {
  2017. "by": {"release": "1A", "environment": "rando_env"},
  2018. "totals": {"sum(session)": 1},
  2019. "series": {"sum(session)": [0, 1]},
  2020. },
  2021. ]
  2022. # Test env condition with NOT IN
  2023. response = self.do_request(
  2024. {
  2025. "project": rando_project.id,
  2026. "statsPeriod": "1d",
  2027. "interval": "1d",
  2028. "field": ["sum(session)"],
  2029. "query": "!environment:[rando_env,rando_enc2]",
  2030. "groupBy": ["release", "environment"],
  2031. "orderBy": "-release.timestamp",
  2032. "per_page": 4,
  2033. }
  2034. )
  2035. assert response.data["groups"] == [
  2036. {
  2037. "by": {"release": "1D", "environment": "production"},
  2038. "totals": {"sum(session)": 1},
  2039. "series": {"sum(session)": [0, 1]},
  2040. },
  2041. {
  2042. "by": {"release": "1C", "environment": "production"},
  2043. "totals": {"sum(session)": 1},
  2044. "series": {"sum(session)": [0, 1]},
  2045. },
  2046. ]
  2047. # Test env condition with invalid OR operation
  2048. response = self.do_request(
  2049. {
  2050. "project": rando_project.id,
  2051. "statsPeriod": "1d",
  2052. "interval": "1d",
  2053. "field": ["sum(session)"],
  2054. "query": "environment:rando_env OR environment:rando_enc2",
  2055. "groupBy": ["release", "environment"],
  2056. "orderBy": "-release.timestamp",
  2057. "per_page": 4,
  2058. }
  2059. )
  2060. assert response.json()["detail"] == "Unable to parse condition with environment"
  2061. @freeze_time(MOCK_DATETIME)
  2062. def test_order_by_without_release_groupby(self):
  2063. rando_project = self.create_project()
  2064. response = self.do_request(
  2065. {
  2066. "project": rando_project.id,
  2067. "statsPeriod": "1d",
  2068. "interval": "1d",
  2069. "query": "session.status:[crashed,errored]",
  2070. "field": ["sum(session)"],
  2071. "orderBy": "-release.timestamp",
  2072. "per_page": 2,
  2073. }
  2074. )
  2075. assert response.data["detail"] == (
  2076. "To sort by release.timestamp, tag release must be in the groupBy"
  2077. )
  2078. @freeze_time(MOCK_DATETIME)
  2079. def test_order_by_release_with_session_status_current_filter(self):
  2080. rando_project = self.create_project()
  2081. release_1a = self.create_release(project=rando_project, version="1A")
  2082. release_1b = self.create_release(project=rando_project, version="1B")
  2083. # Release 1B sessions
  2084. for _ in range(4):
  2085. self.store_session(
  2086. make_session(rando_project, release=release_1b.version, status="crashed")
  2087. )
  2088. for _ in range(10):
  2089. self.store_session(make_session(rando_project, release=release_1b.version))
  2090. for _ in range(3):
  2091. self.store_session(make_session(rando_project, errors=1, release=release_1b.version))
  2092. # Release 1A sessions
  2093. for _ in range(0, 2):
  2094. self.store_session(
  2095. make_session(rando_project, release=release_1a.version, status="crashed")
  2096. )
  2097. self.store_session(make_session(rando_project, release=release_1a.version))
  2098. for _ in range(3):
  2099. self.store_session(make_session(rando_project, errors=1, release=release_1a.version))
  2100. response = self.do_request(
  2101. {
  2102. "project": rando_project.id,
  2103. "statsPeriod": "1d",
  2104. "interval": "1d",
  2105. "query": "session.status:[crashed,errored]",
  2106. "field": ["sum(session)"],
  2107. "groupBy": ["release"],
  2108. "orderBy": "-release.timestamp",
  2109. }
  2110. )
  2111. assert response.data["groups"] == [
  2112. {
  2113. "by": {"release": "1B"},
  2114. "totals": {"sum(session)": 7},
  2115. "series": {"sum(session)": [0, 7]},
  2116. },
  2117. {
  2118. "by": {"release": "1A"},
  2119. "totals": {"sum(session)": 5},
  2120. "series": {"sum(session)": [0, 5]},
  2121. },
  2122. ]