test_organization_sessions.py 87 KB

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