test_organization_sessions.py 87 KB

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