test_organization_sessions.py 87 KB

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