test_organization_sessions.py 87 KB

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