test_organization_sessions.py 87 KB

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