test_organization_sessions.py 87 KB

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