test_organization_events_stats_mep.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445
  1. from __future__ import annotations
  2. from datetime import timedelta
  3. from typing import Any
  4. from unittest import mock
  5. import pytest
  6. from django.urls import reverse
  7. from sentry.models.environment import Environment
  8. from sentry.sentry_metrics.use_case_id_registry import UseCaseID
  9. from sentry.snuba.metrics.extraction import MetricSpecType, OnDemandMetricSpec
  10. from sentry.testutils.cases import MetricsEnhancedPerformanceTestCase
  11. from sentry.testutils.helpers.datetime import before_now, iso_format
  12. from sentry.testutils.silo import region_silo_test
  13. pytestmark = pytest.mark.sentry_metrics
  14. @region_silo_test
  15. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest(
  16. MetricsEnhancedPerformanceTestCase
  17. ):
  18. endpoint = "sentry-api-0-organization-events-stats"
  19. METRIC_STRINGS = [
  20. "foo_transaction",
  21. "d:transactions/measurements.datacenter_memory@pebibyte",
  22. ]
  23. def setUp(self):
  24. super().setUp()
  25. self.login_as(user=self.user)
  26. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  27. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  28. self.url = reverse(
  29. "sentry-api-0-organization-events-stats",
  30. kwargs={"organization_slug": self.project.organization.slug},
  31. )
  32. self.features = {
  33. "organizations:performance-use-metrics": True,
  34. }
  35. self.additional_params = dict()
  36. def do_request(self, data, url=None, features=None):
  37. if features is None:
  38. features = {"organizations:discover-basic": True}
  39. features.update(self.features)
  40. with self.feature(features):
  41. return self.client.get(self.url if url is None else url, data=data, format="json")
  42. # These throughput tests should roughly match the ones in OrganizationEventsStatsEndpointTest
  43. def test_throughput_epm_hour_rollup(self):
  44. # Each of these denotes how many events to create in each hour
  45. event_counts = [6, 0, 6, 3, 0, 3]
  46. for hour, count in enumerate(event_counts):
  47. for minute in range(count):
  48. self.store_transaction_metric(
  49. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  50. )
  51. for axis in ["epm()", "tpm()"]:
  52. response = self.do_request(
  53. data={
  54. "start": iso_format(self.day_ago),
  55. "end": iso_format(self.day_ago + timedelta(hours=6)),
  56. "interval": "1h",
  57. "yAxis": axis,
  58. "project": self.project.id,
  59. "dataset": "metricsEnhanced",
  60. **self.additional_params,
  61. },
  62. )
  63. assert response.status_code == 200, response.content
  64. data = response.data["data"]
  65. assert len(data) == 6
  66. assert response.data["isMetricsData"]
  67. rows = data[0:6]
  68. for test in zip(event_counts, rows):
  69. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  70. def test_throughput_epm_day_rollup(self):
  71. # Each of these denotes how many events to create in each minute
  72. event_counts = [6, 0, 6, 3, 0, 3]
  73. for hour, count in enumerate(event_counts):
  74. for minute in range(count):
  75. self.store_transaction_metric(
  76. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute)
  77. )
  78. for axis in ["epm()", "tpm()"]:
  79. response = self.do_request(
  80. data={
  81. "start": iso_format(self.day_ago),
  82. "end": iso_format(self.day_ago + timedelta(hours=24)),
  83. "interval": "24h",
  84. "yAxis": axis,
  85. "project": self.project.id,
  86. "dataset": "metricsEnhanced",
  87. **self.additional_params,
  88. },
  89. )
  90. assert response.status_code == 200, response.content
  91. data = response.data["data"]
  92. assert len(data) == 2
  93. assert response.data["isMetricsData"]
  94. assert data[0][1][0]["count"] == sum(event_counts) / (86400.0 / 60.0)
  95. def test_throughput_epm_hour_rollup_offset_of_hour(self):
  96. # Each of these denotes how many events to create in each hour
  97. event_counts = [6, 0, 6, 3, 0, 3]
  98. for hour, count in enumerate(event_counts):
  99. for minute in range(count):
  100. self.store_transaction_metric(
  101. 1, timestamp=self.day_ago + timedelta(hours=hour, minutes=minute + 30)
  102. )
  103. for axis in ["tpm()", "epm()"]:
  104. response = self.do_request(
  105. data={
  106. "start": iso_format(self.day_ago + timedelta(minutes=30)),
  107. "end": iso_format(self.day_ago + timedelta(hours=6, minutes=30)),
  108. "interval": "1h",
  109. "yAxis": axis,
  110. "project": self.project.id,
  111. "dataset": "metricsEnhanced",
  112. **self.additional_params,
  113. },
  114. )
  115. assert response.status_code == 200, response.content
  116. data = response.data["data"]
  117. assert len(data) == 6
  118. assert response.data["isMetricsData"]
  119. rows = data[0:6]
  120. for test in zip(event_counts, rows):
  121. assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
  122. def test_throughput_eps_minute_rollup(self):
  123. # Each of these denotes how many events to create in each minute
  124. event_counts = [6, 0, 6, 3, 0, 3]
  125. for minute, count in enumerate(event_counts):
  126. for second in range(count):
  127. self.store_transaction_metric(
  128. 1, timestamp=self.day_ago + timedelta(minutes=minute, seconds=second)
  129. )
  130. for axis in ["eps()", "tps()"]:
  131. response = self.do_request(
  132. data={
  133. "start": iso_format(self.day_ago),
  134. "end": iso_format(self.day_ago + timedelta(minutes=6)),
  135. "interval": "1m",
  136. "yAxis": axis,
  137. "project": self.project.id,
  138. "dataset": "metricsEnhanced",
  139. **self.additional_params,
  140. },
  141. )
  142. assert response.status_code == 200, response.content
  143. data = response.data["data"]
  144. assert len(data) == 6
  145. assert response.data["isMetricsData"]
  146. rows = data[0:6]
  147. for test in zip(event_counts, rows):
  148. assert test[1][1][0]["count"] == test[0] / 60.0
  149. def test_failure_rate(self):
  150. for hour in range(6):
  151. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  152. self.store_transaction_metric(1, tags={"transaction.status": "ok"}, timestamp=timestamp)
  153. if hour < 3:
  154. self.store_transaction_metric(
  155. 1, tags={"transaction.status": "internal_error"}, timestamp=timestamp
  156. )
  157. response = self.do_request(
  158. data={
  159. "start": iso_format(self.day_ago),
  160. "end": iso_format(self.day_ago + timedelta(hours=6)),
  161. "interval": "1h",
  162. "yAxis": ["failure_rate()"],
  163. "project": self.project.id,
  164. "dataset": "metricsEnhanced",
  165. **self.additional_params,
  166. },
  167. )
  168. assert response.status_code == 200, response.content
  169. data = response.data["data"]
  170. assert len(data) == 6
  171. assert response.data["isMetricsData"]
  172. assert [attrs for time, attrs in response.data["data"]] == [
  173. [{"count": 0.5}],
  174. [{"count": 0.5}],
  175. [{"count": 0.5}],
  176. [{"count": 0}],
  177. [{"count": 0}],
  178. [{"count": 0}],
  179. ]
  180. def test_percentiles_multi_axis(self):
  181. for hour in range(6):
  182. timestamp = self.day_ago + timedelta(hours=hour, minutes=30)
  183. self.store_transaction_metric(111, timestamp=timestamp)
  184. self.store_transaction_metric(222, metric="measurements.lcp", timestamp=timestamp)
  185. response = self.do_request(
  186. data={
  187. "start": iso_format(self.day_ago),
  188. "end": iso_format(self.day_ago + timedelta(hours=6)),
  189. "interval": "1h",
  190. "yAxis": ["p75(measurements.lcp)", "p75(transaction.duration)"],
  191. "project": self.project.id,
  192. "dataset": "metricsEnhanced",
  193. **self.additional_params,
  194. },
  195. )
  196. assert response.status_code == 200, response.content
  197. lcp = response.data["p75(measurements.lcp)"]
  198. duration = response.data["p75(transaction.duration)"]
  199. assert len(duration["data"]) == 6
  200. assert duration["isMetricsData"]
  201. assert len(lcp["data"]) == 6
  202. assert lcp["isMetricsData"]
  203. for item in duration["data"]:
  204. assert item[1][0]["count"] == 111
  205. for item in lcp["data"]:
  206. assert item[1][0]["count"] == 222
  207. @mock.patch("sentry.snuba.metrics_enhanced_performance.timeseries_query", return_value={})
  208. def test_multiple_yaxis_only_one_query(self, mock_query):
  209. self.do_request(
  210. data={
  211. "project": self.project.id,
  212. "start": iso_format(self.day_ago),
  213. "end": iso_format(self.day_ago + timedelta(hours=2)),
  214. "interval": "1h",
  215. "yAxis": ["epm()", "eps()", "tpm()", "p50(transaction.duration)"],
  216. "dataset": "metricsEnhanced",
  217. **self.additional_params,
  218. },
  219. )
  220. assert mock_query.call_count == 1
  221. def test_aggregate_function_user_count(self):
  222. self.store_transaction_metric(
  223. 1, metric="user", timestamp=self.day_ago + timedelta(minutes=30)
  224. )
  225. self.store_transaction_metric(
  226. 1, metric="user", timestamp=self.day_ago + timedelta(hours=1, minutes=30)
  227. )
  228. response = self.do_request(
  229. data={
  230. "start": iso_format(self.day_ago),
  231. "end": iso_format(self.day_ago + timedelta(hours=2)),
  232. "interval": "1h",
  233. "yAxis": "count_unique(user)",
  234. "dataset": "metricsEnhanced",
  235. **self.additional_params,
  236. },
  237. )
  238. assert response.status_code == 200, response.content
  239. assert response.data["isMetricsData"]
  240. assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 1}]]
  241. meta = response.data["meta"]
  242. assert meta["isMetricsData"] == response.data["isMetricsData"]
  243. def test_non_mep_query_fallsback(self):
  244. def get_mep(query):
  245. response = self.do_request(
  246. data={
  247. "project": self.project.id,
  248. "start": iso_format(self.day_ago),
  249. "end": iso_format(self.day_ago + timedelta(hours=2)),
  250. "interval": "1h",
  251. "query": query,
  252. "yAxis": ["epm()"],
  253. "dataset": "metricsEnhanced",
  254. **self.additional_params,
  255. },
  256. )
  257. assert response.status_code == 200, response.content
  258. return response.data["isMetricsData"]
  259. assert get_mep(""), "empty query"
  260. assert get_mep("event.type:transaction"), "event type transaction"
  261. assert not get_mep("event.type:error"), "event type error"
  262. assert not get_mep("transaction.duration:<15min"), "outlier filter"
  263. assert get_mep("epm():>0.01"), "throughput filter"
  264. assert not get_mep(
  265. "event.type:transaction OR event.type:error"
  266. ), "boolean with non-mep filter"
  267. assert get_mep(
  268. "event.type:transaction OR transaction:foo_transaction"
  269. ), "boolean with mep filter"
  270. def test_having_condition_with_preventing_aggregates(self):
  271. response = self.do_request(
  272. data={
  273. "project": self.project.id,
  274. "start": iso_format(self.day_ago),
  275. "end": iso_format(self.day_ago + timedelta(hours=2)),
  276. "interval": "1h",
  277. "query": "p95():<5s",
  278. "yAxis": ["epm()"],
  279. "dataset": "metricsEnhanced",
  280. "preventMetricAggregates": "1",
  281. **self.additional_params,
  282. },
  283. )
  284. assert response.status_code == 200, response.content
  285. assert not response.data["isMetricsData"]
  286. meta = response.data["meta"]
  287. assert meta["isMetricsData"] == response.data["isMetricsData"]
  288. def test_explicit_not_mep(self):
  289. response = self.do_request(
  290. data={
  291. "project": self.project.id,
  292. "start": iso_format(self.day_ago),
  293. "end": iso_format(self.day_ago + timedelta(hours=2)),
  294. "interval": "1h",
  295. # Should be a mep able query
  296. "query": "",
  297. "yAxis": ["epm()"],
  298. "metricsEnhanced": "0",
  299. **self.additional_params,
  300. },
  301. )
  302. assert response.status_code == 200, response.content
  303. assert not response.data["isMetricsData"]
  304. meta = response.data["meta"]
  305. assert meta["isMetricsData"] == response.data["isMetricsData"]
  306. def test_sum_transaction_duration(self):
  307. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  308. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  309. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  310. response = self.do_request(
  311. data={
  312. "start": iso_format(self.day_ago),
  313. "end": iso_format(self.day_ago + timedelta(hours=2)),
  314. "interval": "1h",
  315. "yAxis": "sum(transaction.duration)",
  316. "dataset": "metricsEnhanced",
  317. **self.additional_params,
  318. },
  319. )
  320. assert response.status_code == 200, response.content
  321. assert response.data["isMetricsData"]
  322. assert [attrs for time, attrs in response.data["data"]] == [
  323. [{"count": 123}],
  324. [{"count": 1245}],
  325. ]
  326. meta = response.data["meta"]
  327. assert meta["isMetricsData"] == response.data["isMetricsData"]
  328. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  329. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  330. def test_sum_transaction_duration_with_comparison(self):
  331. # We store the data for the previous day (in order to have values for the comparison).
  332. self.store_transaction_metric(
  333. 1, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  334. )
  335. self.store_transaction_metric(
  336. 2, timestamp=self.day_ago - timedelta(days=1) + timedelta(minutes=30)
  337. )
  338. # We store the data for today.
  339. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  340. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(minutes=30))
  341. response = self.do_request(
  342. data={
  343. "start": iso_format(self.day_ago),
  344. "end": iso_format(self.day_ago + timedelta(days=1)),
  345. "interval": "1d",
  346. "yAxis": "sum(transaction.duration)",
  347. "comparisonDelta": 86400,
  348. "dataset": "metricsEnhanced",
  349. **self.additional_params,
  350. },
  351. )
  352. assert response.status_code == 200, response.content
  353. assert response.data["isMetricsData"]
  354. # For some reason, if all tests run, there is some shared state that makes this test have data in the second
  355. # time bucket, which is filled automatically by the zerofilling. In order to avoid this flaky failure, we will
  356. # only check that the first bucket contains the actual data.
  357. assert [attrs for time, attrs in response.data["data"]][0] == [
  358. {"comparisonCount": 3.0, "count": 579.0}
  359. ]
  360. meta = response.data["meta"]
  361. assert meta["isMetricsData"] == response.data["isMetricsData"]
  362. assert meta["fields"] == {"time": "date", "sum_transaction_duration": "duration"}
  363. assert meta["units"] == {"time": None, "sum_transaction_duration": "millisecond"}
  364. def test_custom_measurement(self):
  365. self.store_transaction_metric(
  366. 123,
  367. metric="measurements.bytes_transfered",
  368. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  369. entity="metrics_distributions",
  370. tags={"transaction": "foo_transaction"},
  371. timestamp=self.day_ago + timedelta(minutes=30),
  372. )
  373. self.store_transaction_metric(
  374. 456,
  375. metric="measurements.bytes_transfered",
  376. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  377. entity="metrics_distributions",
  378. tags={"transaction": "foo_transaction"},
  379. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  380. )
  381. self.store_transaction_metric(
  382. 789,
  383. metric="measurements.bytes_transfered",
  384. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  385. entity="metrics_distributions",
  386. tags={"transaction": "foo_transaction"},
  387. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  388. )
  389. response = self.do_request(
  390. data={
  391. "start": iso_format(self.day_ago),
  392. "end": iso_format(self.day_ago + timedelta(hours=2)),
  393. "interval": "1h",
  394. "yAxis": "sum(measurements.datacenter_memory)",
  395. "dataset": "metricsEnhanced",
  396. **self.additional_params,
  397. },
  398. )
  399. assert response.status_code == 200, response.content
  400. assert response.data["isMetricsData"]
  401. assert [attrs for time, attrs in response.data["data"]] == [
  402. [{"count": 123}],
  403. [{"count": 1245}],
  404. ]
  405. meta = response.data["meta"]
  406. assert meta["isMetricsData"] == response.data["isMetricsData"]
  407. assert meta["fields"] == {"time": "date", "sum_measurements_datacenter_memory": "size"}
  408. assert meta["units"] == {"time": None, "sum_measurements_datacenter_memory": "pebibyte"}
  409. def test_does_not_fallback_if_custom_metric_is_out_of_request_time_range(self):
  410. self.store_transaction_metric(
  411. 123,
  412. timestamp=self.day_ago + timedelta(hours=1),
  413. internal_metric="d:transactions/measurements.custom@kibibyte",
  414. entity="metrics_distributions",
  415. )
  416. response = self.do_request(
  417. data={
  418. "start": iso_format(self.day_ago),
  419. "end": iso_format(self.day_ago + timedelta(hours=2)),
  420. "interval": "1h",
  421. "yAxis": "p99(measurements.custom)",
  422. "dataset": "metricsEnhanced",
  423. **self.additional_params,
  424. },
  425. )
  426. meta = response.data["meta"]
  427. assert response.status_code == 200, response.content
  428. assert response.data["isMetricsData"]
  429. assert meta["isMetricsData"]
  430. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  431. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  432. def test_multi_yaxis_custom_measurement(self):
  433. self.store_transaction_metric(
  434. 123,
  435. metric="measurements.bytes_transfered",
  436. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  437. entity="metrics_distributions",
  438. tags={"transaction": "foo_transaction"},
  439. timestamp=self.day_ago + timedelta(minutes=30),
  440. )
  441. self.store_transaction_metric(
  442. 456,
  443. metric="measurements.bytes_transfered",
  444. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  445. entity="metrics_distributions",
  446. tags={"transaction": "foo_transaction"},
  447. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  448. )
  449. self.store_transaction_metric(
  450. 789,
  451. metric="measurements.bytes_transfered",
  452. internal_metric="d:transactions/measurements.datacenter_memory@pebibyte",
  453. entity="metrics_distributions",
  454. tags={"transaction": "foo_transaction"},
  455. timestamp=self.day_ago + timedelta(hours=1, minutes=30),
  456. )
  457. response = self.do_request(
  458. data={
  459. "start": iso_format(self.day_ago),
  460. "end": iso_format(self.day_ago + timedelta(hours=2)),
  461. "interval": "1h",
  462. "yAxis": [
  463. "sum(measurements.datacenter_memory)",
  464. "p50(measurements.datacenter_memory)",
  465. ],
  466. "dataset": "metricsEnhanced",
  467. **self.additional_params,
  468. },
  469. )
  470. assert response.status_code == 200, response.content
  471. sum_data = response.data["sum(measurements.datacenter_memory)"]
  472. p50_data = response.data["p50(measurements.datacenter_memory)"]
  473. assert sum_data["isMetricsData"]
  474. assert p50_data["isMetricsData"]
  475. assert [attrs for time, attrs in sum_data["data"]] == [
  476. [{"count": 123}],
  477. [{"count": 1245}],
  478. ]
  479. assert [attrs for time, attrs in p50_data["data"]] == [
  480. [{"count": 123}],
  481. [{"count": 622.5}],
  482. ]
  483. sum_meta = sum_data["meta"]
  484. assert sum_meta["isMetricsData"] == sum_data["isMetricsData"]
  485. assert sum_meta["fields"] == {
  486. "time": "date",
  487. "sum_measurements_datacenter_memory": "size",
  488. "p50_measurements_datacenter_memory": "size",
  489. }
  490. assert sum_meta["units"] == {
  491. "time": None,
  492. "sum_measurements_datacenter_memory": "pebibyte",
  493. "p50_measurements_datacenter_memory": "pebibyte",
  494. }
  495. p50_meta = p50_data["meta"]
  496. assert p50_meta["isMetricsData"] == p50_data["isMetricsData"]
  497. assert p50_meta["fields"] == {
  498. "time": "date",
  499. "sum_measurements_datacenter_memory": "size",
  500. "p50_measurements_datacenter_memory": "size",
  501. }
  502. assert p50_meta["units"] == {
  503. "time": None,
  504. "sum_measurements_datacenter_memory": "pebibyte",
  505. "p50_measurements_datacenter_memory": "pebibyte",
  506. }
  507. def test_dataset_metrics_does_not_fallback(self):
  508. self.store_transaction_metric(123, timestamp=self.day_ago + timedelta(minutes=30))
  509. self.store_transaction_metric(456, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  510. self.store_transaction_metric(789, timestamp=self.day_ago + timedelta(hours=1, minutes=30))
  511. response = self.do_request(
  512. data={
  513. "start": iso_format(self.day_ago),
  514. "end": iso_format(self.day_ago + timedelta(hours=2)),
  515. "interval": "1h",
  516. "query": "transaction.duration:<5s",
  517. "yAxis": "sum(transaction.duration)",
  518. "dataset": "metrics",
  519. **self.additional_params,
  520. },
  521. )
  522. assert response.status_code == 400, response.content
  523. def test_title_filter(self):
  524. self.store_transaction_metric(
  525. 123,
  526. tags={"transaction": "foo_transaction"},
  527. timestamp=self.day_ago + timedelta(minutes=30),
  528. )
  529. response = self.do_request(
  530. data={
  531. "start": iso_format(self.day_ago),
  532. "end": iso_format(self.day_ago + timedelta(hours=2)),
  533. "interval": "1h",
  534. "query": "title:foo_transaction",
  535. "yAxis": [
  536. "sum(transaction.duration)",
  537. ],
  538. "dataset": "metricsEnhanced",
  539. **self.additional_params,
  540. },
  541. )
  542. assert response.status_code == 200, response.content
  543. data = response.data["data"]
  544. assert [attrs for time, attrs in data] == [
  545. [{"count": 123}],
  546. [{"count": 0}],
  547. ]
  548. def test_transaction_status_unknown_error(self):
  549. self.store_transaction_metric(
  550. 123,
  551. tags={"transaction.status": "unknown"},
  552. timestamp=self.day_ago + timedelta(minutes=30),
  553. )
  554. response = self.do_request(
  555. data={
  556. "start": iso_format(self.day_ago),
  557. "end": iso_format(self.day_ago + timedelta(hours=2)),
  558. "interval": "1h",
  559. "query": "transaction.status:unknown_error",
  560. "yAxis": [
  561. "sum(transaction.duration)",
  562. ],
  563. "dataset": "metricsEnhanced",
  564. **self.additional_params,
  565. },
  566. )
  567. assert response.status_code == 200, response.content
  568. data = response.data["data"]
  569. assert [attrs for time, attrs in data] == [
  570. [{"count": 123}],
  571. [{"count": 0}],
  572. ]
  573. def test_custom_performance_metric_meta_contains_field_and_unit_data(self):
  574. self.store_transaction_metric(
  575. 123,
  576. timestamp=self.day_ago + timedelta(hours=1),
  577. internal_metric="d:transactions/measurements.custom@kibibyte",
  578. entity="metrics_distributions",
  579. )
  580. response = self.do_request(
  581. data={
  582. "start": iso_format(self.day_ago),
  583. "end": iso_format(self.day_ago + timedelta(hours=2)),
  584. "interval": "1h",
  585. "yAxis": "p99(measurements.custom)",
  586. "query": "",
  587. **self.additional_params,
  588. },
  589. )
  590. assert response.status_code == 200
  591. meta = response.data["meta"]
  592. assert meta["fields"] == {"time": "date", "p99_measurements_custom": "size"}
  593. assert meta["units"] == {"time": None, "p99_measurements_custom": "kibibyte"}
  594. def test_multi_series_custom_performance_metric_meta_contains_field_and_unit_data(self):
  595. self.store_transaction_metric(
  596. 123,
  597. timestamp=self.day_ago + timedelta(hours=1),
  598. internal_metric="d:transactions/measurements.custom@kibibyte",
  599. entity="metrics_distributions",
  600. )
  601. self.store_transaction_metric(
  602. 123,
  603. timestamp=self.day_ago + timedelta(hours=1),
  604. internal_metric="d:transactions/measurements.another.custom@pebibyte",
  605. entity="metrics_distributions",
  606. )
  607. response = self.do_request(
  608. data={
  609. "start": iso_format(self.day_ago),
  610. "end": iso_format(self.day_ago + timedelta(hours=2)),
  611. "interval": "1h",
  612. "yAxis": [
  613. "p95(measurements.custom)",
  614. "p99(measurements.custom)",
  615. "p99(measurements.another.custom)",
  616. ],
  617. "query": "",
  618. **self.additional_params,
  619. },
  620. )
  621. assert response.status_code == 200
  622. meta = response.data["p95(measurements.custom)"]["meta"]
  623. assert meta["fields"] == {
  624. "time": "date",
  625. "p95_measurements_custom": "size",
  626. "p99_measurements_custom": "size",
  627. "p99_measurements_another_custom": "size",
  628. }
  629. assert meta["units"] == {
  630. "time": None,
  631. "p95_measurements_custom": "kibibyte",
  632. "p99_measurements_custom": "kibibyte",
  633. "p99_measurements_another_custom": "pebibyte",
  634. }
  635. assert meta == response.data["p99(measurements.custom)"]["meta"]
  636. assert meta == response.data["p99(measurements.another.custom)"]["meta"]
  637. def test_no_top_events_with_project_field(self):
  638. project = self.create_project()
  639. response = self.do_request(
  640. data={
  641. # make sure to query the project with 0 events
  642. "project": project.id,
  643. "start": iso_format(self.day_ago),
  644. "end": iso_format(self.day_ago + timedelta(hours=2)),
  645. "interval": "1h",
  646. "yAxis": "count()",
  647. "orderby": ["-count()"],
  648. "field": ["count()", "project"],
  649. "topEvents": 5,
  650. "dataset": "metrics",
  651. **self.additional_params,
  652. },
  653. )
  654. assert response.status_code == 200, response.content
  655. # When there are no top events, we do not return an empty dict.
  656. # Instead, we return a single zero-filled series for an empty graph.
  657. data = response.data["data"]
  658. assert [attrs for time, attrs in data] == [[{"count": 0}], [{"count": 0}]]
  659. def test_top_events_with_transaction(self):
  660. transaction_spec = [("foo", 100), ("bar", 200), ("baz", 300)]
  661. for offset in range(5):
  662. for transaction, duration in transaction_spec:
  663. self.store_transaction_metric(
  664. duration,
  665. tags={"transaction": f"{transaction}_transaction"},
  666. timestamp=self.day_ago + timedelta(hours=offset, minutes=30),
  667. )
  668. response = self.do_request(
  669. data={
  670. # make sure to query the project with 0 events
  671. "project": self.project.id,
  672. "start": iso_format(self.day_ago),
  673. "end": iso_format(self.day_ago + timedelta(hours=5)),
  674. "interval": "1h",
  675. "yAxis": "p75(transaction.duration)",
  676. "orderby": ["-p75(transaction.duration)"],
  677. "field": ["p75(transaction.duration)", "transaction"],
  678. "topEvents": 5,
  679. "dataset": "metrics",
  680. **self.additional_params,
  681. },
  682. )
  683. assert response.status_code == 200, response.content
  684. for position, (transaction, duration) in enumerate(transaction_spec):
  685. data = response.data[f"{transaction}_transaction"]
  686. chart_data = data["data"]
  687. assert data["order"] == 2 - position
  688. assert [attrs for time, attrs in chart_data] == [[{"count": duration}]] * 5
  689. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithMetricLayer(
  690. OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTest
  691. ):
  692. def setUp(self):
  693. super().setUp()
  694. self.features["organizations:use-metrics-layer"] = True
  695. self.additional_params = {"forceMetricsLayer": "true"}
  696. def test_counter_standard_metric(self):
  697. mri = "c:transactions/usage@none"
  698. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  699. self.store_transaction_metric(
  700. value,
  701. metric=mri,
  702. internal_metric=mri,
  703. entity="metrics_counters",
  704. timestamp=self.day_ago + timedelta(minutes=index),
  705. use_case_id=UseCaseID.CUSTOM,
  706. )
  707. response = self.do_request(
  708. data={
  709. "start": iso_format(self.day_ago),
  710. "end": iso_format(self.day_ago + timedelta(hours=6)),
  711. "interval": "1m",
  712. "yAxis": [f"sum({mri})"],
  713. "project": self.project.id,
  714. "dataset": "metricsEnhanced",
  715. **self.additional_params,
  716. },
  717. )
  718. assert response.status_code == 200, response.content
  719. data = response.data["data"]
  720. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  721. assert value[0]["count"] == expected_value # type:ignore
  722. def test_counter_custom_metric(self):
  723. mri = "c:custom/sentry.process_profile.track_outcome@second"
  724. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  725. self.store_transaction_metric(
  726. value,
  727. metric=mri,
  728. internal_metric=mri,
  729. entity="metrics_counters",
  730. timestamp=self.day_ago + timedelta(hours=index),
  731. use_case_id=UseCaseID.CUSTOM,
  732. )
  733. response = self.do_request(
  734. data={
  735. "start": iso_format(self.day_ago),
  736. "end": iso_format(self.day_ago + timedelta(hours=6)),
  737. "interval": "1h",
  738. "yAxis": [f"sum({mri})"],
  739. "project": self.project.id,
  740. "dataset": "metricsEnhanced",
  741. **self.additional_params,
  742. },
  743. )
  744. assert response.status_code == 200, response.content
  745. data = response.data["data"]
  746. for (_, value), expected_value in zip(data, [10, 20, 30, 40, 50, 60]):
  747. assert value[0]["count"] == expected_value # type:ignore
  748. def test_distribution_custom_metric(self):
  749. mri = "d:custom/sentry.process_profile.track_outcome@second"
  750. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  751. for multiplier in (1, 2, 3):
  752. self.store_transaction_metric(
  753. value * multiplier,
  754. metric=mri,
  755. internal_metric=mri,
  756. entity="metrics_distributions",
  757. timestamp=self.day_ago + timedelta(hours=index),
  758. use_case_id=UseCaseID.CUSTOM,
  759. )
  760. response = self.do_request(
  761. data={
  762. "start": iso_format(self.day_ago),
  763. "end": iso_format(self.day_ago + timedelta(hours=6)),
  764. "interval": "1h",
  765. "yAxis": [f"min({mri})", f"max({mri})", f"p90({mri})"],
  766. "project": self.project.id,
  767. "dataset": "metricsEnhanced",
  768. **self.additional_params,
  769. },
  770. )
  771. assert response.status_code == 200, response.content
  772. data = response.data
  773. min = data[f"min({mri})"]["data"]
  774. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  775. assert value[0]["count"] == expected_value # type:ignore
  776. max = data[f"max({mri})"]["data"]
  777. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  778. assert value[0]["count"] == expected_value # type:ignore
  779. p90 = data[f"p90({mri})"]["data"]
  780. for (_, value), expected_value in zip(p90, [28.0, 56.0, 84.0, 112.0, 140.0, 168.0]):
  781. assert value[0]["count"] == expected_value # type:ignore
  782. def test_set_custom_metric(self):
  783. mri = "s:custom/sentry.process_profile.track_outcome@second"
  784. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  785. # We store each value a second time, since we want to check the de-duplication of sets.
  786. for i in range(0, 2):
  787. self.store_transaction_metric(
  788. value,
  789. metric=mri,
  790. internal_metric=mri,
  791. entity="metrics_sets",
  792. timestamp=self.day_ago + timedelta(hours=index),
  793. use_case_id=UseCaseID.CUSTOM,
  794. )
  795. response = self.do_request(
  796. data={
  797. "start": iso_format(self.day_ago),
  798. "end": iso_format(self.day_ago + timedelta(hours=6)),
  799. "interval": "1h",
  800. "yAxis": [f"count_unique({mri})"],
  801. "project": self.project.id,
  802. "dataset": "metricsEnhanced",
  803. **self.additional_params,
  804. },
  805. )
  806. assert response.status_code == 200, response.content
  807. data = response.data["data"]
  808. for (_, value), expected_value in zip(data, [1, 1, 1, 1, 1, 1]):
  809. assert value[0]["count"] == expected_value # type:ignore
  810. def test_gauge_custom_metric(self):
  811. mri = "g:custom/sentry.process_profile.track_outcome@second"
  812. for index, value in enumerate((10, 20, 30, 40, 50, 60)):
  813. for multiplier in (1, 3):
  814. self.store_transaction_metric(
  815. value * multiplier,
  816. metric=mri,
  817. internal_metric=mri,
  818. entity="metrics_gauges",
  819. # When multiple gauges are merged, in order to make the `last` merge work deterministically it's
  820. # better to have the gauges with different timestamps so that the last value is always the same.
  821. timestamp=self.day_ago + timedelta(hours=index, minutes=multiplier),
  822. use_case_id=UseCaseID.CUSTOM,
  823. )
  824. response = self.do_request(
  825. data={
  826. "start": iso_format(self.day_ago),
  827. "end": iso_format(self.day_ago + timedelta(hours=6)),
  828. "interval": "1h",
  829. "yAxis": [
  830. f"min({mri})",
  831. f"max({mri})",
  832. f"last({mri})",
  833. f"sum({mri})",
  834. f"count({mri})",
  835. ],
  836. "project": self.project.id,
  837. "dataset": "metricsEnhanced",
  838. **self.additional_params,
  839. },
  840. )
  841. assert response.status_code == 200, response.content
  842. data = response.data
  843. min = data[f"min({mri})"]["data"]
  844. for (_, value), expected_value in zip(min, [10.0, 20.0, 30.0, 40.0, 50.0, 60.0]):
  845. assert value[0]["count"] == expected_value # type:ignore
  846. max = data[f"max({mri})"]["data"]
  847. for (_, value), expected_value in zip(max, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  848. assert value[0]["count"] == expected_value # type:ignore
  849. last = data[f"last({mri})"]["data"]
  850. for (_, value), expected_value in zip(last, [30.0, 60.0, 90.0, 120.0, 150.0, 180.0]):
  851. assert value[0]["count"] == expected_value # type:ignore
  852. sum = data[f"sum({mri})"]["data"]
  853. for (_, value), expected_value in zip(sum, [40.0, 80.0, 120.0, 160.0, 200.0, 240.0]):
  854. assert value[0]["count"] == expected_value # type:ignore
  855. count = data[f"count({mri})"]["data"]
  856. for (_, value), expected_value in zip(count, [40, 80, 120, 160, 200, 240]):
  857. assert value[0]["count"] == expected_value # type:ignore
  858. @region_silo_test
  859. class OrganizationEventsStatsMetricsEnhancedPerformanceEndpointTestWithOnDemandWidgets(
  860. MetricsEnhancedPerformanceTestCase
  861. ):
  862. endpoint = "sentry-api-0-organization-events-stats"
  863. def setUp(self):
  864. super().setUp()
  865. self.login_as(user=self.user)
  866. self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
  867. self.DEFAULT_METRIC_TIMESTAMP = self.day_ago
  868. Environment.get_or_create(self.project, "production")
  869. self.url = reverse(
  870. "sentry-api-0-organization-events-stats",
  871. kwargs={"organization_slug": self.project.organization.slug},
  872. )
  873. self.features = {"organizations:on-demand-metrics-extraction-widgets": True}
  874. def do_request(self, data, url=None, features=None):
  875. if features is None:
  876. features = {"organizations:discover-basic": True}
  877. features.update(self.features)
  878. with self.feature(features):
  879. return self.client.get(self.url if url is None else url, data=data, format="json")
  880. def test_top_events_wrong_on_demand_type(self):
  881. query = "transaction.duration:>=100"
  882. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  883. response = self.do_request(
  884. data={
  885. "project": self.project.id,
  886. "start": iso_format(self.day_ago),
  887. "end": iso_format(self.day_ago + timedelta(hours=2)),
  888. "interval": "1h",
  889. "orderby": ["-count()"],
  890. "environment": "production",
  891. "query": query,
  892. "yAxis": yAxis,
  893. "field": [
  894. "count()",
  895. ],
  896. "topEvents": 5,
  897. "dataset": "metrics",
  898. "useOnDemandMetrics": "true",
  899. "onDemandType": "not_real",
  900. },
  901. )
  902. assert response.status_code == 400, response.content
  903. def test_top_events_works_without_on_demand_type(self):
  904. query = "transaction.duration:>=100"
  905. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  906. response = self.do_request(
  907. data={
  908. "project": self.project.id,
  909. "start": iso_format(self.day_ago),
  910. "end": iso_format(self.day_ago + timedelta(hours=2)),
  911. "interval": "1h",
  912. "orderby": ["-count()"],
  913. "environment": "production",
  914. "query": query,
  915. "yAxis": yAxis,
  916. "field": [
  917. "count()",
  918. ],
  919. "topEvents": 5,
  920. "dataset": "metrics",
  921. "useOnDemandMetrics": "true",
  922. },
  923. )
  924. assert response.status_code == 200, response.content
  925. def test_top_events_with_transaction_on_demand(self):
  926. field = "count()"
  927. field_two = "count_web_vitals(measurements.lcp, good)"
  928. groupbys = ["customtag1", "customtag2"]
  929. query = "transaction.duration:>=100"
  930. spec = OnDemandMetricSpec(
  931. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  932. )
  933. spec_two = OnDemandMetricSpec(
  934. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  935. )
  936. for hour in range(0, 5):
  937. self.store_on_demand_metric(
  938. hour * 62 * 24,
  939. spec=spec,
  940. additional_tags={
  941. "customtag1": "foo",
  942. "customtag2": "red",
  943. "environment": "production",
  944. },
  945. timestamp=self.day_ago + timedelta(hours=hour),
  946. )
  947. self.store_on_demand_metric(
  948. hour * 60 * 24,
  949. spec=spec_two,
  950. additional_tags={
  951. "customtag1": "bar",
  952. "customtag2": "blue",
  953. "environment": "production",
  954. },
  955. timestamp=self.day_ago + timedelta(hours=hour),
  956. )
  957. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  958. response = self.do_request(
  959. data={
  960. "project": self.project.id,
  961. "start": iso_format(self.day_ago),
  962. "end": iso_format(self.day_ago + timedelta(hours=2)),
  963. "interval": "1h",
  964. "orderby": ["-count()"],
  965. "environment": "production",
  966. "query": query,
  967. "yAxis": yAxis,
  968. "field": [
  969. "count()",
  970. "count_web_vitals(measurements.lcp, good)",
  971. "customtag1",
  972. "customtag2",
  973. ],
  974. "topEvents": 5,
  975. "dataset": "metricsEnhanced",
  976. "useOnDemandMetrics": "true",
  977. "onDemandType": "dynamic_query",
  978. },
  979. )
  980. assert response.status_code == 200, response.content
  981. groups = [
  982. ("foo,red", "count()", 0.0, 1488.0),
  983. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  984. ("bar,blue", "count()", 0.0, 0.0),
  985. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  986. ]
  987. assert len(response.data.keys()) == 2
  988. for group_count in groups:
  989. group, agg, row1, row2 = group_count
  990. row_data = response.data[group][agg]["data"][:2]
  991. assert [attrs for _, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  992. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  993. assert response.data[group]["isMetricsExtractedData"]
  994. def test_top_events_with_transaction_on_demand_and_no_environment(self):
  995. field = "count()"
  996. field_two = "count_web_vitals(measurements.lcp, good)"
  997. groupbys = ["customtag1", "customtag2"]
  998. query = "transaction.duration:>=100"
  999. spec = OnDemandMetricSpec(
  1000. field=field, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1001. )
  1002. spec_two = OnDemandMetricSpec(
  1003. field=field_two, groupbys=groupbys, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1004. )
  1005. for hour in range(0, 5):
  1006. self.store_on_demand_metric(
  1007. hour * 62 * 24,
  1008. spec=spec,
  1009. additional_tags={
  1010. "customtag1": "foo",
  1011. "customtag2": "red",
  1012. "environment": "production",
  1013. },
  1014. timestamp=self.day_ago + timedelta(hours=hour),
  1015. )
  1016. self.store_on_demand_metric(
  1017. hour * 60 * 24,
  1018. spec=spec_two,
  1019. additional_tags={
  1020. "customtag1": "bar",
  1021. "customtag2": "blue",
  1022. "environment": "production",
  1023. },
  1024. timestamp=self.day_ago + timedelta(hours=hour),
  1025. )
  1026. yAxis = ["count()", "count_web_vitals(measurements.lcp, good)"]
  1027. response = self.do_request(
  1028. data={
  1029. "project": self.project.id,
  1030. "start": iso_format(self.day_ago),
  1031. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1032. "interval": "1h",
  1033. "orderby": ["-count()"],
  1034. "query": query,
  1035. "yAxis": yAxis,
  1036. "field": [
  1037. "count()",
  1038. "count_web_vitals(measurements.lcp, good)",
  1039. "customtag1",
  1040. "customtag2",
  1041. ],
  1042. "topEvents": 5,
  1043. "dataset": "metricsEnhanced",
  1044. "useOnDemandMetrics": "true",
  1045. "onDemandType": "dynamic_query",
  1046. },
  1047. )
  1048. assert response.status_code == 200, response.content
  1049. groups = [
  1050. ("foo,red", "count()", 0.0, 1488.0),
  1051. ("foo,red", "count_web_vitals(measurements.lcp, good)", 0.0, 0.0),
  1052. ("bar,blue", "count()", 0.0, 0.0),
  1053. ("bar,blue", "count_web_vitals(measurements.lcp, good)", 0.0, 1440.0),
  1054. ]
  1055. assert len(response.data.keys()) == 2
  1056. for group_count in groups:
  1057. group, agg, row1, row2 = group_count
  1058. row_data = response.data[group][agg]["data"][:2]
  1059. assert [attrs for time, attrs in row_data] == [[{"count": row1}], [{"count": row2}]]
  1060. assert response.data[group][agg]["meta"]["isMetricsExtractedData"]
  1061. assert response.data[group]["isMetricsExtractedData"]
  1062. def test_timeseries_on_demand_with_multiple_percentiles(self):
  1063. field = "p75(measurements.fcp)"
  1064. field_two = "p75(measurements.lcp)"
  1065. query = "transaction.duration:>=100"
  1066. spec = OnDemandMetricSpec(field=field, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY)
  1067. spec_two = OnDemandMetricSpec(
  1068. field=field_two, query=query, spec_type=MetricSpecType.DYNAMIC_QUERY
  1069. )
  1070. assert (
  1071. spec._query_str_for_hash
  1072. == "event.measurements.fcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1073. )
  1074. assert (
  1075. spec_two._query_str_for_hash
  1076. == "event.measurements.lcp.value;{'name': 'event.duration', 'op': 'gte', 'value': 100.0}"
  1077. )
  1078. for count in range(0, 4):
  1079. self.store_on_demand_metric(
  1080. count * 100,
  1081. spec=spec,
  1082. timestamp=self.day_ago + timedelta(hours=1),
  1083. )
  1084. self.store_on_demand_metric(
  1085. count * 200.0,
  1086. spec=spec_two,
  1087. timestamp=self.day_ago + timedelta(hours=1),
  1088. )
  1089. yAxis = [field, field_two]
  1090. response = self.do_request(
  1091. data={
  1092. "project": self.project.id,
  1093. "start": iso_format(self.day_ago),
  1094. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1095. "interval": "1h",
  1096. "orderby": [field],
  1097. "query": query,
  1098. "yAxis": yAxis,
  1099. "dataset": "metricsEnhanced",
  1100. "useOnDemandMetrics": "true",
  1101. "onDemandType": "dynamic_query",
  1102. },
  1103. )
  1104. assert response.status_code == 200, response.content
  1105. assert response.data["p75(measurements.fcp)"]["meta"]["isMetricsExtractedData"]
  1106. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1107. assert [attrs for time, attrs in response.data["p75(measurements.fcp)"]["data"]] == [
  1108. [{"count": 0}],
  1109. [{"count": 225.0}],
  1110. ]
  1111. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsExtractedData"]
  1112. assert response.data["p75(measurements.lcp)"]["meta"]["isMetricsData"]
  1113. assert [attrs for time, attrs in response.data["p75(measurements.lcp)"]["data"]] == [
  1114. [{"count": 0}],
  1115. [{"count": 450.0}],
  1116. ]
  1117. def test_apdex_issue(self):
  1118. field = "apdex(300)"
  1119. groupbys = ["group_tag"]
  1120. query = "transaction.duration:>=100"
  1121. spec = OnDemandMetricSpec(
  1122. field=field,
  1123. groupbys=groupbys,
  1124. query=query,
  1125. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1126. )
  1127. for hour in range(0, 5):
  1128. self.store_on_demand_metric(
  1129. 1,
  1130. spec=spec,
  1131. additional_tags={
  1132. "group_tag": "group_one",
  1133. "environment": "production",
  1134. "satisfaction": "tolerable",
  1135. },
  1136. timestamp=self.day_ago + timedelta(hours=hour),
  1137. )
  1138. self.store_on_demand_metric(
  1139. 1,
  1140. spec=spec,
  1141. additional_tags={
  1142. "group_tag": "group_two",
  1143. "environment": "production",
  1144. "satisfaction": "satisfactory",
  1145. },
  1146. timestamp=self.day_ago + timedelta(hours=hour),
  1147. )
  1148. response = self.do_request(
  1149. data={
  1150. "dataset": "metricsEnhanced",
  1151. "environment": "production",
  1152. "excludeOther": 1,
  1153. "field": [field, "group_tag"],
  1154. "start": iso_format(self.day_ago),
  1155. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1156. "interval": "1h",
  1157. "orderby": f"-{field}",
  1158. "partial": 1,
  1159. "project": self.project.id,
  1160. "query": query,
  1161. "topEvents": 5,
  1162. "yAxis": field,
  1163. "onDemandType": "dynamic_query",
  1164. "useOnDemandMetrics": "true",
  1165. },
  1166. )
  1167. assert response.status_code == 200, response.content
  1168. assert response.data["group_one"]["meta"]["isMetricsExtractedData"] is True
  1169. assert [attrs for time, attrs in response.data["group_one"]["data"]] == [
  1170. [{"count": 0.5}],
  1171. [{"count": 0.5}],
  1172. ]
  1173. def test_glob_http_referer_on_demand(self):
  1174. agg = "count()"
  1175. network_id_tag = "networkId"
  1176. url = "https://sentry.io"
  1177. query = f'http.url:{url}/*/foo/bar/* http.referer:"{url}/*/bar/*" event.type:transaction'
  1178. spec = OnDemandMetricSpec(
  1179. field=agg,
  1180. groupbys=[network_id_tag],
  1181. query=query,
  1182. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1183. )
  1184. assert spec.to_metric_spec(self.project) == {
  1185. "category": "transaction",
  1186. "mri": "c:transactions/on_demand@none",
  1187. "field": None,
  1188. "tags": [
  1189. {"key": "query_hash", "value": "ac241f56"},
  1190. {"key": "networkId", "field": "event.tags.networkId"},
  1191. {"key": "environment", "field": "event.environment"},
  1192. ],
  1193. "condition": {
  1194. "op": "and",
  1195. "inner": [
  1196. {
  1197. "op": "glob",
  1198. "name": "event.request.url",
  1199. "value": ["https://sentry.io/*/foo/bar/*"],
  1200. },
  1201. {
  1202. "op": "glob",
  1203. "name": "event.request.headers.Referer",
  1204. "value": ["https://sentry.io/*/bar/*"],
  1205. },
  1206. ],
  1207. },
  1208. }
  1209. for hour in range(0, 5):
  1210. self.store_on_demand_metric(
  1211. 1,
  1212. spec=spec,
  1213. additional_tags={network_id_tag: "1234"},
  1214. timestamp=self.day_ago + timedelta(hours=hour),
  1215. )
  1216. self.store_on_demand_metric(
  1217. 1,
  1218. spec=spec,
  1219. additional_tags={network_id_tag: "5678"},
  1220. timestamp=self.day_ago + timedelta(hours=hour),
  1221. )
  1222. response = self.do_request(
  1223. data={
  1224. "dataset": "metricsEnhanced",
  1225. "field": [network_id_tag, agg],
  1226. "start": iso_format(self.day_ago),
  1227. "end": iso_format(self.day_ago + timedelta(hours=5)),
  1228. "onDemandType": "dynamic_query",
  1229. "orderby": f"-{agg}",
  1230. "interval": "1d",
  1231. "partial": 1,
  1232. "query": query,
  1233. "referrer": "api.dashboards.widget.bar-chart",
  1234. "project": self.project.id,
  1235. "topEvents": 2,
  1236. "useOnDemandMetrics": "true",
  1237. "yAxis": agg,
  1238. },
  1239. )
  1240. assert response.status_code == 200, response.content
  1241. for datum in response.data.values():
  1242. assert datum["meta"] == {
  1243. "dataset": "metricsEnhanced",
  1244. "datasetReason": "unchanged",
  1245. "fields": {},
  1246. "isMetricsData": False,
  1247. "isMetricsExtractedData": True,
  1248. "tips": {},
  1249. "units": {},
  1250. }
  1251. def _test_is_metrics_extracted_data(
  1252. self, params: dict[str, Any], expected_on_demand_query: bool, dataset: str
  1253. ) -> None:
  1254. features = {"organizations:on-demand-metrics-extraction": True}
  1255. spec = OnDemandMetricSpec(
  1256. field="count()",
  1257. query="transaction.duration:>1s",
  1258. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1259. )
  1260. self.store_on_demand_metric(1, spec=spec)
  1261. response = self.do_request(params, features=features)
  1262. assert response.status_code == 200, response.content
  1263. meta = response.data["meta"]
  1264. # This is the main thing we want to test for
  1265. assert meta.get("isMetricsExtractedData", False) is expected_on_demand_query
  1266. assert meta["dataset"] == dataset
  1267. return meta
  1268. def test_is_metrics_extracted_data_is_included(self):
  1269. self._test_is_metrics_extracted_data(
  1270. {
  1271. "dataset": "metricsEnhanced",
  1272. "query": "transaction.duration:>=91",
  1273. "useOnDemandMetrics": "true",
  1274. "yAxis": "count()",
  1275. },
  1276. expected_on_demand_query=True,
  1277. dataset="metricsEnhanced",
  1278. )
  1279. def test_group_by_transaction(self):
  1280. field = "count()"
  1281. groupbys = ["transaction"]
  1282. query = "transaction.duration:>=100"
  1283. spec = OnDemandMetricSpec(
  1284. field=field,
  1285. groupbys=groupbys,
  1286. query=query,
  1287. spec_type=MetricSpecType.DYNAMIC_QUERY,
  1288. )
  1289. for hour in range(0, 2):
  1290. self.store_on_demand_metric(
  1291. (hour + 1) * 5,
  1292. spec=spec,
  1293. additional_tags={
  1294. "transaction": "/performance",
  1295. "environment": "production",
  1296. },
  1297. timestamp=self.day_ago + timedelta(hours=hour),
  1298. )
  1299. response = self.do_request(
  1300. data={
  1301. "dataset": "metricsEnhanced",
  1302. "environment": "production",
  1303. "excludeOther": 1,
  1304. "field": [field, "transaction"],
  1305. "start": iso_format(self.day_ago),
  1306. "end": iso_format(self.day_ago + timedelta(hours=2)),
  1307. "interval": "1h",
  1308. "orderby": f"-{field}",
  1309. "partial": 1,
  1310. "project": self.project.id,
  1311. "query": query,
  1312. "topEvents": 5,
  1313. "yAxis": field,
  1314. "onDemandType": "dynamic_query",
  1315. "useOnDemandMetrics": "true",
  1316. },
  1317. )
  1318. assert response.status_code == 200, response.content
  1319. assert response.data["/performance"]["meta"]["isMetricsExtractedData"] is True
  1320. assert [attrs for time, attrs in response.data["/performance"]["data"]] == [
  1321. [{"count": 5.0}],
  1322. [{"count": 10.0}],
  1323. ]