test_organization_sessions.py 87 KB

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