test_organization_sessions.py 86 KB

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