test_organization_sessions.py 87 KB

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