test_organization_sessions.py 88 KB

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