test_organization_events.py 202 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287
  1. import math
  2. from base64 import b64encode
  3. from datetime import timedelta
  4. from unittest import mock
  5. import pytest
  6. from django.test import override_settings
  7. from django.urls import reverse
  8. from django.utils import timezone
  9. from freezegun import freeze_time
  10. from pytz import utc
  11. from snuba_sdk.column import Column
  12. from snuba_sdk.function import Function
  13. from sentry.discover.models import TeamKeyTransaction
  14. from sentry.models import ApiKey, ProjectTeam, ProjectTransactionThreshold, ReleaseStages
  15. from sentry.models.transaction_threshold import (
  16. ProjectTransactionThresholdOverride,
  17. TransactionMetric,
  18. )
  19. from sentry.search.events import constants
  20. from sentry.testutils import APITestCase, SnubaTestCase
  21. from sentry.testutils.helpers import parse_link_header
  22. from sentry.testutils.helpers.datetime import before_now, iso_format
  23. from sentry.testutils.silo import region_silo_test
  24. from sentry.testutils.skips import requires_not_arm64
  25. from sentry.types.issues import GroupType
  26. from sentry.utils import json
  27. from sentry.utils.samples import load_data
  28. from sentry.utils.snuba import QueryExecutionError, QueryIllegalTypeOfArgument, RateLimitExceeded
  29. MAX_QUERYABLE_TRANSACTION_THRESHOLDS = 1
  30. @region_silo_test
  31. class OrganizationEventsEndpointTest(APITestCase, SnubaTestCase):
  32. viewname = "sentry-api-0-organization-events"
  33. referrer = "api.organization-events"
  34. def setUp(self):
  35. super().setUp()
  36. self.ten_mins_ago = iso_format(before_now(minutes=10))
  37. self.eleven_mins_ago = iso_format(before_now(minutes=11))
  38. self.transaction_data = load_data("transaction", timestamp=before_now(minutes=10))
  39. self.features = {}
  40. def client_get(self, *args, **kwargs):
  41. return self.client.get(*args, **kwargs)
  42. def reverse_url(self):
  43. return reverse(
  44. self.viewname,
  45. kwargs={"organization_slug": self.organization.slug},
  46. )
  47. def do_request(self, query, features=None):
  48. if features is None:
  49. features = {"organizations:discover-basic": True}
  50. features.update(self.features)
  51. self.login_as(user=self.user)
  52. with self.feature(features):
  53. return self.client_get(self.reverse_url(), query, format="json")
  54. def load_data(self, platform="transaction", timestamp=None, duration=None, **kwargs):
  55. if timestamp is None:
  56. timestamp = before_now(minutes=1)
  57. start_timestamp = None
  58. if duration is not None:
  59. start_timestamp = timestamp - duration
  60. start_timestamp = start_timestamp - timedelta(
  61. microseconds=start_timestamp.microsecond % 1000
  62. )
  63. return load_data(platform, timestamp=timestamp, start_timestamp=start_timestamp, **kwargs)
  64. def test_no_projects(self):
  65. response = self.do_request({})
  66. assert response.status_code == 200, response.content
  67. assert len(response.data) == 0
  68. def test_api_key_request(self):
  69. self.store_event(
  70. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  71. project_id=self.project.id,
  72. )
  73. # Project ID cannot be inferred when using an org API key, so that must
  74. # be passed in the parameters
  75. api_key = ApiKey.objects.create(organization=self.organization, scope_list=["org:read"])
  76. query = {"field": ["project.name", "environment"], "project": [self.project.id]}
  77. url = self.reverse_url()
  78. response = self.client_get(
  79. url,
  80. query,
  81. format="json",
  82. HTTP_AUTHORIZATION=b"Basic " + b64encode(f"{api_key.key}:".encode()),
  83. )
  84. assert response.status_code == 200, response.content
  85. assert len(response.data["data"]) == 1
  86. assert response.data["data"][0]["project.name"] == self.project.slug
  87. def test_performance_view_feature(self):
  88. self.store_event(
  89. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group1"]},
  90. project_id=self.project.id,
  91. )
  92. query = {"field": ["id", "project.id"], "project": [self.project.id]}
  93. response = self.do_request(query)
  94. assert response.status_code == 200
  95. assert len(response.data["data"]) == 1
  96. def test_multi_project_feature_gate_rejection(self):
  97. team = self.create_team(organization=self.organization, members=[self.user])
  98. project = self.create_project(organization=self.organization, teams=[team])
  99. project2 = self.create_project(organization=self.organization, teams=[team])
  100. query = {"field": ["id", "project.id"], "project": [project.id, project2.id]}
  101. response = self.do_request(query)
  102. assert response.status_code == 400
  103. assert "events from multiple projects" in response.data["detail"]
  104. def test_invalid_search_terms(self):
  105. self.create_project()
  106. query = {"field": ["id"], "query": "hi \n there"}
  107. response = self.do_request(query)
  108. assert response.status_code == 400, response.content
  109. assert (
  110. response.data["detail"]
  111. == "Parse error at 'hi \n ther' (column 4). This is commonly caused by unmatched parentheses. Enclose any text in double quotes."
  112. )
  113. def test_invalid_trace_span(self):
  114. self.create_project()
  115. query = {"field": ["id"], "query": "trace.span:invalid"}
  116. response = self.do_request(query)
  117. assert response.status_code == 400, response.content
  118. assert (
  119. response.data["detail"]
  120. == "trace.span must be a valid 16 character hex (containing only digits, or a-f characters)"
  121. )
  122. query = {"field": ["id"], "query": "trace.parent_span:invalid"}
  123. response = self.do_request(query)
  124. assert response.status_code == 400, response.content
  125. assert (
  126. response.data["detail"]
  127. == "trace.parent_span must be a valid 16 character hex (containing only digits, or a-f characters)"
  128. )
  129. query = {"field": ["id"], "query": "trace.span:*"}
  130. response = self.do_request(query)
  131. assert response.status_code == 400, response.content
  132. assert (
  133. response.data["detail"] == "Wildcard conditions are not permitted on `trace.span` field"
  134. )
  135. query = {"field": ["id"], "query": "trace.parent_span:*"}
  136. response = self.do_request(query)
  137. assert response.status_code == 400, response.content
  138. assert (
  139. response.data["detail"]
  140. == "Wildcard conditions are not permitted on `trace.parent_span` field"
  141. )
  142. def test_has_trace_context(self):
  143. self.store_event(
  144. data={
  145. "event_id": "a" * 32,
  146. "message": "how to make fast",
  147. "timestamp": self.ten_mins_ago,
  148. "contexts": {
  149. "trace": {
  150. "span_id": "a" * 16,
  151. "trace_id": "b" * 32,
  152. },
  153. },
  154. },
  155. project_id=self.project.id,
  156. )
  157. query = {"field": ["id", "trace.parent_span"], "query": "has:trace.span"}
  158. response = self.do_request(query)
  159. assert response.status_code == 200, response.content
  160. assert len(response.data["data"]) == 1
  161. assert response.data["data"][0]["id"] == "a" * 32
  162. query = {"field": ["id"], "query": "has:trace.parent_span"}
  163. response = self.do_request(query)
  164. assert response.status_code == 200, response.content
  165. assert len(response.data["data"]) == 0
  166. def test_not_has_trace_context(self):
  167. self.store_event(
  168. data={
  169. "event_id": "a" * 32,
  170. "message": "how to make fast",
  171. "timestamp": self.ten_mins_ago,
  172. "contexts": {
  173. "trace": {
  174. "span_id": "a" * 16,
  175. "trace_id": "b" * 32,
  176. },
  177. },
  178. },
  179. project_id=self.project.id,
  180. )
  181. query = {"field": ["id", "trace.parent_span"], "query": "!has:trace.span"}
  182. response = self.do_request(query)
  183. assert response.status_code == 200, response.content
  184. assert len(response.data["data"]) == 0
  185. query = {"field": ["id"], "query": "!has:trace.parent_span"}
  186. response = self.do_request(query)
  187. assert response.status_code == 200, response.content
  188. assert len(response.data["data"]) == 1
  189. assert response.data["data"][0]["id"] == "a" * 32
  190. def test_parent_span_id_in_context(self):
  191. self.store_event(
  192. data={
  193. "event_id": "a" * 32,
  194. "message": "how to make fast",
  195. "timestamp": self.ten_mins_ago,
  196. "contexts": {
  197. "trace": {
  198. "span_id": "a" * 16,
  199. "trace_id": "b" * 32,
  200. "parent_span_id": "c" * 16,
  201. },
  202. },
  203. },
  204. project_id=self.project.id,
  205. )
  206. query = {"field": ["id"], "query": f"trace.parent_span:{'c' * 16}"}
  207. response = self.do_request(query)
  208. assert response.status_code == 200, response.content
  209. assert len(response.data["data"]) == 1
  210. assert response.data["data"][0]["id"] == "a" * 32
  211. @mock.patch("sentry.search.events.builder.raw_snql_query")
  212. def test_handling_snuba_errors(self, mock_snql_query):
  213. self.create_project()
  214. mock_snql_query.side_effect = RateLimitExceeded("test")
  215. query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
  216. response = self.do_request(query)
  217. assert response.status_code == 400, response.content
  218. assert response.data["detail"] == constants.TIMEOUT_ERROR_MESSAGE
  219. mock_snql_query.side_effect = QueryExecutionError("test")
  220. query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
  221. response = self.do_request(query)
  222. assert response.status_code == 500, response.content
  223. assert response.data["detail"] == "Internal error. Your query failed to run."
  224. mock_snql_query.side_effect = QueryIllegalTypeOfArgument("test")
  225. query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
  226. response = self.do_request(query)
  227. assert response.status_code == 400, response.content
  228. assert response.data["detail"] == "Invalid query. Argument to function is wrong type."
  229. def test_out_of_retention(self):
  230. self.create_project()
  231. with self.options({"system.event-retention-days": 10}):
  232. query = {
  233. "field": ["id", "timestamp"],
  234. "orderby": ["-timestamp", "-id"],
  235. "start": iso_format(before_now(days=20)),
  236. "end": iso_format(before_now(days=15)),
  237. }
  238. response = self.do_request(query)
  239. assert response.status_code == 400, response.content
  240. assert response.data["detail"] == "Invalid date range. Please try a more recent date range."
  241. def test_raw_data(self):
  242. self.store_event(
  243. data={
  244. "event_id": "a" * 32,
  245. "environment": "staging",
  246. "timestamp": self.eleven_mins_ago,
  247. "user": {"ip_address": "127.0.0.1", "email": "foo@example.com"},
  248. },
  249. project_id=self.project.id,
  250. )
  251. self.store_event(
  252. data={
  253. "event_id": "b" * 32,
  254. "environment": "staging",
  255. "timestamp": self.ten_mins_ago,
  256. "user": {"ip_address": "127.0.0.1", "email": "foo@example.com"},
  257. },
  258. project_id=self.project.id,
  259. )
  260. query = {
  261. "field": ["id", "project.id", "user.email", "user.ip", "timestamp"],
  262. "orderby": "-timestamp",
  263. }
  264. response = self.do_request(query)
  265. assert response.status_code == 200, response.content
  266. data = response.data["data"]
  267. assert len(data) == 2
  268. assert data[0]["id"] == "b" * 32
  269. assert data[0]["project.id"] == self.project.id
  270. assert data[0]["user.email"] == "foo@example.com"
  271. assert "project.name" not in data[0], "project.id does not auto select name"
  272. assert "project" not in data[0]
  273. meta = response.data["meta"]
  274. field_meta = meta["fields"]
  275. assert field_meta["id"] == "string"
  276. assert field_meta["user.email"] == "string"
  277. assert field_meta["user.ip"] == "string"
  278. assert field_meta["timestamp"] == "date"
  279. def test_project_name(self):
  280. self.store_event(
  281. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  282. project_id=self.project.id,
  283. )
  284. query = {"field": ["project.name", "environment"]}
  285. response = self.do_request(query)
  286. assert response.status_code == 200, response.content
  287. assert len(response.data["data"]) == 1
  288. assert response.data["data"][0]["project.name"] == self.project.slug
  289. assert "project.id" not in response.data["data"][0]
  290. assert response.data["data"][0]["environment"] == "staging"
  291. def test_project_without_name(self):
  292. self.store_event(
  293. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  294. project_id=self.project.id,
  295. )
  296. query = {"field": ["project", "environment"]}
  297. response = self.do_request(query)
  298. assert response.status_code == 200, response.content
  299. assert len(response.data["data"]) == 1
  300. assert response.data["data"][0]["project"] == self.project.slug
  301. assert response.data["meta"]["fields"]["project"] == "string"
  302. assert "project.id" not in response.data["data"][0]
  303. assert response.data["data"][0]["environment"] == "staging"
  304. def test_project_in_query(self):
  305. self.store_event(
  306. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  307. project_id=self.project.id,
  308. )
  309. query = {
  310. "field": ["project", "count()"],
  311. "query": f'project:"{self.project.slug}"',
  312. "statsPeriod": "14d",
  313. }
  314. response = self.do_request(query)
  315. assert response.status_code == 200, response.content
  316. assert len(response.data["data"]) == 1
  317. assert response.data["data"][0]["project"] == self.project.slug
  318. assert "project.id" not in response.data["data"][0]
  319. def test_project_in_query_not_in_header(self):
  320. project = self.create_project()
  321. other_project = self.create_project()
  322. self.store_event(
  323. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  324. project_id=project.id,
  325. )
  326. query = {
  327. "field": ["project", "count()"],
  328. "query": 'project:"%s"' % project.slug,
  329. "statsPeriod": "14d",
  330. "project": other_project.id,
  331. }
  332. response = self.do_request(query)
  333. assert response.status_code == 400, response.content
  334. assert (
  335. response.data["detail"]
  336. == f"Invalid query. Project(s) {project.slug} do not exist or are not actively selected."
  337. )
  338. def test_project_in_query_does_not_exist(self):
  339. self.create_project()
  340. query = {"field": ["project", "count()"], "query": "project:morty", "statsPeriod": "14d"}
  341. response = self.do_request(query)
  342. assert response.status_code == 400, response.content
  343. assert (
  344. response.data["detail"]
  345. == "Invalid query. Project(s) morty do not exist or are not actively selected."
  346. )
  347. def test_not_project_in_query_but_in_header(self):
  348. team = self.create_team(organization=self.organization, members=[self.user])
  349. project = self.create_project(organization=self.organization, teams=[team])
  350. project2 = self.create_project(organization=self.organization, teams=[team])
  351. self.store_event(
  352. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group1"]},
  353. project_id=project.id,
  354. )
  355. self.store_event(
  356. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group2"]},
  357. project_id=project2.id,
  358. )
  359. query = {
  360. "field": ["id", "project.id"],
  361. "project": [project.id],
  362. "query": f"!project:{project2.slug}",
  363. }
  364. response = self.do_request(query)
  365. assert response.status_code == 200
  366. assert response.data["data"] == [{"id": "a" * 32, "project.id": project.id}]
  367. def test_not_project_in_query_with_all_projects(self):
  368. team = self.create_team(organization=self.organization, members=[self.user])
  369. project = self.create_project(organization=self.organization, teams=[team])
  370. project2 = self.create_project(organization=self.organization, teams=[team])
  371. self.store_event(
  372. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group1"]},
  373. project_id=project.id,
  374. )
  375. self.store_event(
  376. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group2"]},
  377. project_id=project2.id,
  378. )
  379. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  380. query = {
  381. "field": ["id", "project.id"],
  382. "project": [-1],
  383. "query": f"!project:{project2.slug}",
  384. }
  385. response = self.do_request(query, features=features)
  386. assert response.status_code == 200
  387. assert response.data["data"] == [{"id": "a" * 32, "project.id": project.id}]
  388. def test_project_condition_used_for_automatic_filters(self):
  389. self.store_event(
  390. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  391. project_id=self.project.id,
  392. )
  393. query = {
  394. "field": ["project", "count()"],
  395. "query": f'project:"{self.project.slug}"',
  396. "statsPeriod": "14d",
  397. }
  398. response = self.do_request(query)
  399. assert response.status_code == 200, response.content
  400. assert len(response.data["data"]) == 1
  401. assert response.data["data"][0]["project"] == self.project.slug
  402. assert "project.id" not in response.data["data"][0]
  403. def test_auto_insert_project_name_when_event_id_present(self):
  404. self.store_event(
  405. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  406. project_id=self.project.id,
  407. )
  408. query = {"field": ["id"], "statsPeriod": "1h"}
  409. response = self.do_request(query)
  410. assert response.status_code == 200, response.content
  411. assert response.data["data"] == [{"project.name": self.project.slug, "id": "a" * 32}]
  412. def test_auto_insert_project_name_when_event_id_present_with_aggregate(self):
  413. self.store_event(
  414. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  415. project_id=self.project.id,
  416. )
  417. query = {"field": ["id", "count()"], "statsPeriod": "1h"}
  418. response = self.do_request(query)
  419. assert response.status_code == 200, response.content
  420. assert response.data["data"] == [
  421. {"project.name": self.project.slug, "id": "a" * 32, "count()": 1}
  422. ]
  423. def test_performance_issue_ids_filter(self):
  424. data = load_data(
  425. platform="transaction",
  426. timestamp=before_now(minutes=10),
  427. start_timestamp=before_now(minutes=11),
  428. fingerprint=[f"{GroupType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES.value}-group1"],
  429. )
  430. event = self.store_event(data=data, project_id=self.project.id)
  431. query = {
  432. "field": ["count()"],
  433. "statsPeriod": "2h",
  434. "query": f"project:{self.project.slug} performance.issue_ids:{event.groups[0].id}",
  435. }
  436. response = self.do_request(query)
  437. assert response.status_code == 200, response.content
  438. assert response.data["data"][0]["count()"] == 1
  439. def test_has_performance_issue_ids(self):
  440. data = load_data(
  441. platform="transaction",
  442. fingerprint=[f"{GroupType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES.value}-group1"],
  443. )
  444. self.store_event(data=data, project_id=self.project.id)
  445. query = {
  446. "field": ["count()"],
  447. "statsPeriod": "1h",
  448. "query": "has:performance.issue_ids",
  449. }
  450. response = self.do_request(query)
  451. assert response.status_code == 200, response.content
  452. assert response.data["data"][0]["count()"] == 1
  453. query = {
  454. "field": ["count()"],
  455. "statsPeriod": "1h",
  456. "query": "!has:performance.issue_ids",
  457. }
  458. response = self.do_request(query)
  459. assert response.status_code == 200, response.content
  460. assert response.data["data"][0]["count()"] == 0
  461. def test_performance_issue_ids_undefined(self):
  462. query = {
  463. "field": ["count()"],
  464. "statsPeriod": "2h",
  465. "query": "performance.issue_ids:undefined",
  466. "project": [self.project.id],
  467. }
  468. response = self.do_request(query)
  469. assert response.status_code == 400, response.content
  470. def test_performance_issue_ids_array_with_undefined(self):
  471. query = {
  472. "field": ["count()"],
  473. "statsPeriod": "2h",
  474. "query": "performance.issue_ids:[1,2,3,undefined]",
  475. "project": [self.project.id],
  476. }
  477. response = self.do_request(query)
  478. assert response.status_code == 400, response.content
  479. def test_performance_short_group_id(self):
  480. project = self.create_project(name="foo bar")
  481. data = load_data(
  482. "transaction",
  483. fingerprint=[f"{GroupType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES.value}-group1"],
  484. )
  485. event = self.store_event(data=data, project_id=project.id)
  486. query = {
  487. "field": ["count()"],
  488. "statsPeriod": "1h",
  489. "query": f"project:{project.slug} issue:{event.groups[0].qualified_short_id}",
  490. }
  491. response = self.do_request(query)
  492. assert response.status_code == 200, response.content
  493. assert response.data["data"][0]["count()"] == 1
  494. def test_multiple_performance_short_group_ids_filter(self):
  495. project = self.create_project(name="foo bar")
  496. data1 = load_data(
  497. "transaction",
  498. fingerprint=[f"{GroupType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES.value}-group1"],
  499. )
  500. event1 = self.store_event(data=data1, project_id=project.id)
  501. data2 = load_data(
  502. "transaction",
  503. fingerprint=[f"{GroupType.PERFORMANCE_N_PLUS_ONE_DB_QUERIES.value}-group2"],
  504. )
  505. event2 = self.store_event(data=data2, project_id=project.id)
  506. query = {
  507. "field": ["count()"],
  508. "statsPeriod": "1h",
  509. "query": f"project:{project.slug} issue:[{event1.groups[0].qualified_short_id},{event2.groups[0].qualified_short_id}]",
  510. }
  511. response = self.do_request(query)
  512. assert response.status_code == 200, response.content
  513. assert response.data["data"][0]["count()"] == 2
  514. def test_event_id_with_in_search(self):
  515. self.store_event(
  516. data={"event_id": "a" * 32, "environment": "staging1", "timestamp": self.ten_mins_ago},
  517. project_id=self.project.id,
  518. )
  519. self.store_event(
  520. data={"event_id": "b" * 32, "environment": "staging2", "timestamp": self.ten_mins_ago},
  521. project_id=self.project.id,
  522. )
  523. # Should not show up
  524. self.store_event(
  525. data={"event_id": "c" * 32, "environment": "staging3", "timestamp": self.ten_mins_ago},
  526. project_id=self.project.id,
  527. )
  528. query = {
  529. "field": ["id", "environment"],
  530. "statsPeriod": "1h",
  531. "query": f"id:[{'a' * 32}, {'b' * 32}]",
  532. "orderby": "environment",
  533. }
  534. response = self.do_request(query)
  535. assert response.status_code == 200, response.content
  536. assert len(response.data["data"]) == 2
  537. assert response.data["data"][0]["id"] == "a" * 32
  538. assert response.data["data"][1]["id"] == "b" * 32
  539. def test_user_search(self):
  540. self.transaction_data["user"] = {
  541. "email": "foo@example.com",
  542. "id": "123",
  543. "ip_address": "127.0.0.1",
  544. "username": "foo",
  545. }
  546. self.store_event(self.transaction_data, project_id=self.project.id)
  547. fields = {
  548. "email": "user.email",
  549. "id": "user.id",
  550. "ip_address": "user.ip",
  551. "username": "user.username",
  552. }
  553. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  554. for key, value in self.transaction_data["user"].items():
  555. field = fields[key]
  556. query = {
  557. "field": ["project", "user"],
  558. "query": f"{field}:{value}",
  559. "statsPeriod": "14d",
  560. }
  561. response = self.do_request(query, features=features)
  562. assert response.status_code == 200, response.content
  563. assert len(response.data["data"]) == 1
  564. assert response.data["data"][0]["project"] == self.project.slug
  565. assert response.data["data"][0]["user"] == "id:123"
  566. def test_has_user(self):
  567. self.store_event(self.transaction_data, project_id=self.project.id)
  568. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  569. for value in self.transaction_data["user"].values():
  570. query = {"field": ["project", "user"], "query": "has:user", "statsPeriod": "14d"}
  571. response = self.do_request(query, features=features)
  572. assert response.status_code == 200, response.content
  573. assert len(response.data["data"]) == 1
  574. assert response.data["data"][0]["user"] == "ip:{}".format(
  575. self.transaction_data["user"]["ip_address"]
  576. )
  577. def test_team_param_no_access(self):
  578. org = self.create_organization(
  579. owner=self.user, # use other user as owner
  580. name="foo",
  581. flags=0, # disable default allow_joinleave
  582. )
  583. project = self.create_project(name="baz", organization=org)
  584. user = self.create_user()
  585. self.login_as(user=user, superuser=False)
  586. team = self.create_team(organization=org, name="Team Bar")
  587. project.add_team(team)
  588. self.store_event(
  589. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group1"]},
  590. project_id=project.id,
  591. )
  592. query = {"field": ["id", "project.id"], "project": [project.id], "team": [team.id]}
  593. response = self.do_request(query)
  594. assert response.status_code == 403, response.content
  595. assert response.data["detail"] == "You do not have permission to perform this action."
  596. def test_team_is_nan(self):
  597. query = {"field": ["id"], "project": [self.project.id], "team": [math.nan]}
  598. response = self.do_request(query)
  599. assert response.status_code == 400, response.content
  600. assert response.data["detail"] == "Invalid Team ID: nan"
  601. def test_comparison_operators_on_numeric_field(self):
  602. event = self.store_event(
  603. {"timestamp": iso_format(before_now(minutes=1))}, project_id=self.project.id
  604. )
  605. query = {"field": ["issue"], "query": f"issue.id:>{event.group.id - 1}"}
  606. response = self.do_request(query)
  607. assert response.status_code == 200, response.content
  608. assert len(response.data["data"]) == 1
  609. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  610. query = {"field": ["issue"], "query": f"issue.id:>{event.group.id}"}
  611. response = self.do_request(query)
  612. assert response.status_code == 200, response.content
  613. assert len(response.data["data"]) == 0
  614. def test_negation_on_numeric_field_excludes_issue(self):
  615. event = self.store_event({"timestamp": self.ten_mins_ago}, project_id=self.project.id)
  616. query = {"field": ["issue"], "query": f"issue.id:{event.group.id}"}
  617. response = self.do_request(query)
  618. assert response.status_code == 200, response.content
  619. assert len(response.data["data"]) == 1
  620. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  621. query = {"field": ["issue"], "query": f"!issue.id:{event.group.id}"}
  622. response = self.do_request(query)
  623. assert response.status_code == 200, response.content
  624. assert len(response.data["data"]) == 0
  625. def test_negation_on_numeric_in_filter_excludes_issue(self):
  626. event = self.store_event({"timestamp": self.ten_mins_ago}, project_id=self.project.id)
  627. query = {"field": ["issue"], "query": f"issue.id:[{event.group.id}]"}
  628. response = self.do_request(query)
  629. assert response.status_code == 200, response.content
  630. assert len(response.data["data"]) == 1
  631. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  632. query = {"field": ["issue"], "query": f"!issue.id:[{event.group.id}]"}
  633. response = self.do_request(query)
  634. assert response.status_code == 200, response.content
  635. assert len(response.data["data"]) == 0
  636. def test_negation_on_duration_filter_excludes_transaction(self):
  637. event = self.store_event(self.transaction_data, project_id=self.project.id)
  638. duration = int(event.data.get("timestamp") - event.data.get("start_timestamp")) * 1000
  639. query = {"field": ["transaction"], "query": f"transaction.duration:{duration}"}
  640. response = self.do_request(query)
  641. assert response.status_code == 200, response.content
  642. assert len(response.data["data"]) == 1
  643. assert response.data["data"][0]["id"] == event.event_id
  644. query = {"field": ["transaction"], "query": f"!transaction.duration:{duration}"}
  645. response = self.do_request(query)
  646. assert response.status_code == 200, response.content
  647. assert len(response.data["data"]) == 0
  648. def test_has_issue(self):
  649. event = self.store_event({"timestamp": self.ten_mins_ago}, project_id=self.project.id)
  650. self.store_event(self.transaction_data, project_id=self.project.id)
  651. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  652. # should only show 1 event of type default
  653. query = {"field": ["project", "issue"], "query": "has:issue", "statsPeriod": "14d"}
  654. response = self.do_request(query, features=features)
  655. assert response.status_code == 200, response.content
  656. assert len(response.data["data"]) == 1
  657. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  658. # should only show 1 event of type default
  659. query = {
  660. "field": ["project", "issue"],
  661. "query": "event.type:default has:issue",
  662. "statsPeriod": "14d",
  663. }
  664. response = self.do_request(query, features=features)
  665. assert response.status_code == 200, response.content
  666. assert len(response.data["data"]) == 1
  667. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  668. # should show no results because no the default event has an issue
  669. query = {
  670. "field": ["project", "issue"],
  671. "query": "event.type:default !has:issue",
  672. "statsPeriod": "14d",
  673. }
  674. response = self.do_request(query, features=features)
  675. assert response.status_code == 200, response.content
  676. assert len(response.data["data"]) == 0
  677. # should show no results because no transactions have issues
  678. query = {
  679. "field": ["project", "issue"],
  680. "query": "event.type:transaction has:issue",
  681. "statsPeriod": "14d",
  682. }
  683. response = self.do_request(query, features=features)
  684. assert response.status_code == 200, response.content
  685. assert len(response.data["data"]) == 0
  686. # should only show 1 event of type transaction since they don't have issues
  687. query = {
  688. "field": ["project", "issue"],
  689. "query": "event.type:transaction !has:issue",
  690. "statsPeriod": "14d",
  691. }
  692. response = self.do_request(query, features=features)
  693. assert response.status_code == 200, response.content
  694. assert len(response.data["data"]) == 1
  695. assert response.data["data"][0]["issue"] == "unknown"
  696. @pytest.mark.skip("Cannot look up group_id of transaction events")
  697. def test_unknown_issue(self):
  698. event = self.store_event({"timestamp": self.ten_mins_ago}, project_id=self.project.id)
  699. self.store_event(self.transaction_data, project_id=self.project.id)
  700. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  701. query = {"field": ["project", "issue"], "query": "issue:unknown", "statsPeriod": "14d"}
  702. response = self.do_request(query, features=features)
  703. assert response.status_code == 200, response.content
  704. assert len(response.data["data"]) == 1
  705. assert response.data["data"][0]["issue"] == "unknown"
  706. query = {"field": ["project", "issue"], "query": "!issue:unknown", "statsPeriod": "14d"}
  707. response = self.do_request(query, features=features)
  708. assert response.status_code == 200, response.content
  709. assert len(response.data["data"]) == 1
  710. assert response.data["data"][0]["issue"] == event.group.qualified_short_id
  711. def test_negative_user_search(self):
  712. user_data = {"email": "foo@example.com", "id": "123", "username": "foo"}
  713. # Load an event with data that shouldn't match
  714. data = self.transaction_data.copy()
  715. data["transaction"] = "/transactions/nomatch"
  716. event_user = user_data.copy()
  717. event_user["id"] = "undefined"
  718. data["user"] = event_user
  719. self.store_event(data, project_id=self.project.id)
  720. # Load a matching event
  721. data = self.transaction_data.copy()
  722. data["transaction"] = "/transactions/matching"
  723. data["user"] = user_data
  724. self.store_event(data, project_id=self.project.id)
  725. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  726. query = {
  727. "field": ["project", "user"],
  728. "query": '!user:"id:undefined"',
  729. "statsPeriod": "14d",
  730. }
  731. response = self.do_request(query, features=features)
  732. assert response.status_code == 200, response.content
  733. assert len(response.data["data"]) == 1
  734. assert response.data["data"][0]["user"] == "id:{}".format(user_data["id"])
  735. assert "user.email" not in response.data["data"][0]
  736. assert "user.id" not in response.data["data"][0]
  737. def test_not_project_in_query(self):
  738. project1 = self.create_project()
  739. project2 = self.create_project()
  740. self.store_event(
  741. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  742. project_id=project1.id,
  743. )
  744. self.store_event(
  745. data={"event_id": "b" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  746. project_id=project2.id,
  747. )
  748. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  749. query = {
  750. "field": ["project", "count()"],
  751. "query": '!project:"%s"' % project1.slug,
  752. "statsPeriod": "14d",
  753. }
  754. response = self.do_request(query, features=features)
  755. assert response.status_code == 200, response.content
  756. assert len(response.data["data"]) == 1
  757. assert response.data["data"][0]["project"] == project2.slug
  758. assert "project.id" not in response.data["data"][0]
  759. def test_error_handled_condition(self):
  760. prototype = self.load_data(platform="android-ndk")
  761. events = (
  762. ("a" * 32, "not handled", False),
  763. ("b" * 32, "was handled", True),
  764. ("c" * 32, "undefined", None),
  765. )
  766. for event in events:
  767. prototype["event_id"] = event[0]
  768. prototype["message"] = event[1]
  769. prototype["exception"]["values"][0]["value"] = event[1]
  770. prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
  771. prototype["timestamp"] = self.ten_mins_ago
  772. self.store_event(data=prototype, project_id=self.project.id)
  773. with self.feature("organizations:discover-basic"):
  774. query = {
  775. "field": ["message", "error.handled"],
  776. "query": "error.handled:0",
  777. "orderby": "message",
  778. }
  779. response = self.do_request(query)
  780. assert response.status_code == 200, response.data
  781. assert 1 == len(response.data["data"])
  782. assert 0 == response.data["data"][0]["error.handled"]
  783. with self.feature("organizations:discover-basic"):
  784. query = {
  785. "field": ["message", "error.handled"],
  786. "query": "error.handled:1",
  787. "orderby": "message",
  788. }
  789. response = self.do_request(query)
  790. assert response.status_code == 200, response.data
  791. assert 2 == len(response.data["data"])
  792. assert 1 == response.data["data"][0]["error.handled"]
  793. assert 1 == response.data["data"][1]["error.handled"]
  794. def test_error_unhandled_condition(self):
  795. prototype = self.load_data(platform="android-ndk")
  796. events = (
  797. ("a" * 32, "not handled", False),
  798. ("b" * 32, "was handled", True),
  799. ("c" * 32, "undefined", None),
  800. )
  801. for event in events:
  802. prototype["event_id"] = event[0]
  803. prototype["message"] = event[1]
  804. prototype["exception"]["values"][0]["value"] = event[1]
  805. prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
  806. prototype["timestamp"] = self.ten_mins_ago
  807. self.store_event(data=prototype, project_id=self.project.id)
  808. with self.feature("organizations:discover-basic"):
  809. query = {
  810. "field": ["message", "error.unhandled", "error.handled"],
  811. "query": "error.unhandled:true",
  812. "orderby": "message",
  813. }
  814. response = self.do_request(query)
  815. assert response.status_code == 200, response.data
  816. assert 1 == len(response.data["data"])
  817. assert 0 == response.data["data"][0]["error.handled"]
  818. assert 1 == response.data["data"][0]["error.unhandled"]
  819. with self.feature("organizations:discover-basic"):
  820. query = {
  821. "field": ["message", "error.handled", "error.unhandled"],
  822. "query": "error.unhandled:false",
  823. "orderby": "message",
  824. }
  825. response = self.do_request(query)
  826. assert response.status_code == 200, response.data
  827. assert 2 == len(response.data["data"])
  828. assert 1 == response.data["data"][0]["error.handled"]
  829. assert 0 == response.data["data"][0]["error.unhandled"]
  830. assert 1 == response.data["data"][1]["error.handled"]
  831. assert 0 == response.data["data"][1]["error.unhandled"]
  832. def test_groupby_error_handled_and_unhandled(self):
  833. prototype = self.load_data(platform="android-ndk")
  834. events = (
  835. ("a" * 32, "not handled", False),
  836. ("b" * 32, "was handled", True),
  837. ("c" * 32, "undefined", None),
  838. )
  839. for event in events:
  840. prototype["event_id"] = event[0]
  841. prototype["message"] = event[1]
  842. prototype["exception"]["values"][0]["value"] = event[1]
  843. prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
  844. prototype["timestamp"] = self.ten_mins_ago
  845. self.store_event(data=prototype, project_id=self.project.id)
  846. with self.feature("organizations:discover-basic"):
  847. query = {
  848. "field": ["error.handled", "count()"],
  849. "query": "event.type:error",
  850. }
  851. response = self.do_request(query)
  852. assert response.status_code == 200, response.data
  853. assert 2 == len(response.data["data"])
  854. assert 0 == response.data["data"][0]["error.handled"]
  855. assert 1 == response.data["data"][0]["count()"]
  856. assert 1 == response.data["data"][1]["error.handled"]
  857. assert 2 == response.data["data"][1]["count()"]
  858. with self.feature("organizations:discover-basic"):
  859. query = {
  860. "field": ["error.unhandled", "count()"],
  861. "query": "event.type:error",
  862. }
  863. response = self.do_request(query)
  864. assert response.status_code == 200, response.data
  865. assert 2 == len(response.data["data"])
  866. assert 0 == response.data["data"][0]["error.unhandled"]
  867. assert 2 == response.data["data"][0]["count()"]
  868. assert 1 == response.data["data"][1]["error.unhandled"]
  869. assert 1 == response.data["data"][1]["count()"]
  870. def test_implicit_groupby(self):
  871. self.store_event(
  872. data={
  873. "event_id": "a" * 32,
  874. "timestamp": self.eleven_mins_ago,
  875. "fingerprint": ["group_1"],
  876. },
  877. project_id=self.project.id,
  878. )
  879. event1 = self.store_event(
  880. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_1"]},
  881. project_id=self.project.id,
  882. )
  883. event2 = self.store_event(
  884. data={"event_id": "c" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_2"]},
  885. project_id=self.project.id,
  886. )
  887. query = {"field": ["count(id)", "project.id", "issue.id"], "orderby": "issue.id"}
  888. response = self.do_request(query)
  889. assert response.status_code == 200, response.content
  890. assert len(response.data["data"]) == 2
  891. data = response.data["data"]
  892. assert data[0] == {
  893. "project.id": self.project.id,
  894. "issue.id": event1.group_id,
  895. "count(id)": 2,
  896. }
  897. assert data[1] == {
  898. "project.id": self.project.id,
  899. "issue.id": event2.group_id,
  900. "count(id)": 1,
  901. }
  902. meta = response.data["meta"]["fields"]
  903. assert meta["count(id)"] == "integer"
  904. def test_orderby(self):
  905. self.store_event(
  906. data={"event_id": "a" * 32, "timestamp": self.eleven_mins_ago},
  907. project_id=self.project.id,
  908. )
  909. self.store_event(
  910. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago}, project_id=self.project.id
  911. )
  912. self.store_event(
  913. data={"event_id": "c" * 32, "timestamp": self.ten_mins_ago}, project_id=self.project.id
  914. )
  915. query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
  916. response = self.do_request(query)
  917. assert response.status_code == 200, response.content
  918. data = response.data["data"]
  919. assert data[0]["id"] == "c" * 32
  920. assert data[1]["id"] == "b" * 32
  921. assert data[2]["id"] == "a" * 32
  922. def test_sort_title(self):
  923. self.store_event(
  924. data={"event_id": "a" * 32, "message": "zlast", "timestamp": self.eleven_mins_ago},
  925. project_id=self.project.id,
  926. )
  927. self.store_event(
  928. data={"event_id": "b" * 32, "message": "second", "timestamp": self.ten_mins_ago},
  929. project_id=self.project.id,
  930. )
  931. self.store_event(
  932. data={"event_id": "c" * 32, "message": "first", "timestamp": self.ten_mins_ago},
  933. project_id=self.project.id,
  934. )
  935. query = {"field": ["id", "title"], "sort": "title"}
  936. response = self.do_request(query)
  937. assert response.status_code == 200, response.content
  938. data = response.data["data"]
  939. assert data[0]["id"] == "c" * 32
  940. assert data[1]["id"] == "b" * 32
  941. assert data[2]["id"] == "a" * 32
  942. def test_sort_invalid(self):
  943. self.create_project()
  944. query = {"field": ["id"], "sort": "garbage"}
  945. response = self.do_request(query)
  946. assert response.status_code == 400
  947. assert "sort by" in response.data["detail"]
  948. def test_latest_release_alias(self):
  949. event1 = self.store_event(
  950. data={"event_id": "a" * 32, "timestamp": self.eleven_mins_ago, "release": "0.8"},
  951. project_id=self.project.id,
  952. )
  953. query = {"field": ["issue.id", "release"], "query": "release:latest"}
  954. response = self.do_request(query)
  955. assert response.status_code == 200, response.content
  956. data = response.data["data"]
  957. assert data[0]["issue.id"] == event1.group_id
  958. assert data[0]["release"] == "0.8"
  959. event2 = self.store_event(
  960. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "release": "0.9"},
  961. project_id=self.project.id,
  962. )
  963. query = {"field": ["issue.id", "release"], "query": "release:latest"}
  964. response = self.do_request(query)
  965. assert response.status_code == 200, response.content
  966. data = response.data["data"]
  967. assert data[0]["issue.id"] == event2.group_id
  968. assert data[0]["release"] == "0.9"
  969. def test_semver(self):
  970. release_1 = self.create_release(version="test@1.2.3")
  971. release_2 = self.create_release(version="test@1.2.4")
  972. release_3 = self.create_release(version="test@1.2.5")
  973. release_1_e_1 = self.store_event(
  974. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  975. project_id=self.project.id,
  976. ).event_id
  977. release_1_e_2 = self.store_event(
  978. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  979. project_id=self.project.id,
  980. ).event_id
  981. release_2_e_1 = self.store_event(
  982. data={"release": release_2.version, "timestamp": self.ten_mins_ago},
  983. project_id=self.project.id,
  984. ).event_id
  985. release_2_e_2 = self.store_event(
  986. data={"release": release_2.version, "timestamp": self.ten_mins_ago},
  987. project_id=self.project.id,
  988. ).event_id
  989. release_3_e_1 = self.store_event(
  990. data={"release": release_3.version, "timestamp": self.ten_mins_ago},
  991. project_id=self.project.id,
  992. ).event_id
  993. release_3_e_2 = self.store_event(
  994. data={"release": release_3.version, "timestamp": self.ten_mins_ago},
  995. project_id=self.project.id,
  996. ).event_id
  997. query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:>1.2.3"}
  998. response = self.do_request(query)
  999. assert response.status_code == 200, response.content
  1000. assert {r["id"] for r in response.data["data"]} == {
  1001. release_2_e_1,
  1002. release_2_e_2,
  1003. release_3_e_1,
  1004. release_3_e_2,
  1005. }
  1006. query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:>=1.2.3"}
  1007. response = self.do_request(query)
  1008. assert response.status_code == 200, response.content
  1009. assert {r["id"] for r in response.data["data"]} == {
  1010. release_1_e_1,
  1011. release_1_e_2,
  1012. release_2_e_1,
  1013. release_2_e_2,
  1014. release_3_e_1,
  1015. release_3_e_2,
  1016. }
  1017. query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:<1.2.4"}
  1018. response = self.do_request(query)
  1019. assert response.status_code == 200, response.content
  1020. assert {r["id"] for r in response.data["data"]} == {
  1021. release_1_e_1,
  1022. release_1_e_2,
  1023. }
  1024. query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:1.2.3"}
  1025. response = self.do_request(query)
  1026. assert response.status_code == 200, response.content
  1027. assert {r["id"] for r in response.data["data"]} == {
  1028. release_1_e_1,
  1029. release_1_e_2,
  1030. }
  1031. query = {"field": ["id"], "query": f"!{constants.SEMVER_ALIAS}:1.2.3"}
  1032. response = self.do_request(query)
  1033. assert response.status_code == 200, response.content
  1034. assert {r["id"] for r in response.data["data"]} == {
  1035. release_2_e_1,
  1036. release_2_e_2,
  1037. release_3_e_1,
  1038. release_3_e_2,
  1039. }
  1040. def test_release_stage(self):
  1041. replaced_release = self.create_release(
  1042. version="replaced_release",
  1043. environments=[self.environment],
  1044. adopted=timezone.now(),
  1045. unadopted=timezone.now(),
  1046. )
  1047. adopted_release = self.create_release(
  1048. version="adopted_release",
  1049. environments=[self.environment],
  1050. adopted=timezone.now(),
  1051. )
  1052. self.create_release(version="not_adopted_release", environments=[self.environment])
  1053. adopted_release_e_1 = self.store_event(
  1054. data={
  1055. "release": adopted_release.version,
  1056. "timestamp": self.ten_mins_ago,
  1057. "environment": self.environment.name,
  1058. },
  1059. project_id=self.project.id,
  1060. ).event_id
  1061. adopted_release_e_2 = self.store_event(
  1062. data={
  1063. "release": adopted_release.version,
  1064. "timestamp": self.ten_mins_ago,
  1065. "environment": self.environment.name,
  1066. },
  1067. project_id=self.project.id,
  1068. ).event_id
  1069. replaced_release_e_1 = self.store_event(
  1070. data={
  1071. "release": replaced_release.version,
  1072. "timestamp": self.ten_mins_ago,
  1073. "environment": self.environment.name,
  1074. },
  1075. project_id=self.project.id,
  1076. ).event_id
  1077. replaced_release_e_2 = self.store_event(
  1078. data={
  1079. "release": replaced_release.version,
  1080. "timestamp": self.ten_mins_ago,
  1081. "environment": self.environment.name,
  1082. },
  1083. project_id=self.project.id,
  1084. ).event_id
  1085. query = {
  1086. "field": ["id"],
  1087. "query": f"{constants.RELEASE_STAGE_ALIAS}:{ReleaseStages.ADOPTED}",
  1088. "environment": [self.environment.name],
  1089. }
  1090. response = self.do_request(query)
  1091. assert response.status_code == 200, response.content
  1092. assert {r["id"] for r in response.data["data"]} == {
  1093. adopted_release_e_1,
  1094. adopted_release_e_2,
  1095. }
  1096. query = {
  1097. "field": ["id"],
  1098. "query": f"!{constants.RELEASE_STAGE_ALIAS}:{ReleaseStages.LOW_ADOPTION}",
  1099. "environment": [self.environment.name],
  1100. }
  1101. response = self.do_request(query)
  1102. assert response.status_code == 200, response.content
  1103. assert {r["id"] for r in response.data["data"]} == {
  1104. adopted_release_e_1,
  1105. adopted_release_e_2,
  1106. replaced_release_e_1,
  1107. replaced_release_e_2,
  1108. }
  1109. query = {
  1110. "field": ["id"],
  1111. "query": f"{constants.RELEASE_STAGE_ALIAS}:[{ReleaseStages.ADOPTED}, {ReleaseStages.REPLACED}]",
  1112. "environment": [self.environment.name],
  1113. }
  1114. response = self.do_request(query)
  1115. assert response.status_code == 200, response.content
  1116. assert {r["id"] for r in response.data["data"]} == {
  1117. adopted_release_e_1,
  1118. adopted_release_e_2,
  1119. replaced_release_e_1,
  1120. replaced_release_e_2,
  1121. }
  1122. def test_semver_package(self):
  1123. release_1 = self.create_release(version="test@1.2.3")
  1124. release_2 = self.create_release(version="test2@1.2.4")
  1125. release_1_e_1 = self.store_event(
  1126. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  1127. project_id=self.project.id,
  1128. ).event_id
  1129. release_1_e_2 = self.store_event(
  1130. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  1131. project_id=self.project.id,
  1132. ).event_id
  1133. release_2_e_1 = self.store_event(
  1134. data={"release": release_2.version, "timestamp": self.ten_mins_ago},
  1135. project_id=self.project.id,
  1136. ).event_id
  1137. query = {"field": ["id"], "query": f"{constants.SEMVER_PACKAGE_ALIAS}:test"}
  1138. response = self.do_request(query)
  1139. assert response.status_code == 200, response.content
  1140. assert {r["id"] for r in response.data["data"]} == {
  1141. release_1_e_1,
  1142. release_1_e_2,
  1143. }
  1144. query = {"field": ["id"], "query": f"{constants.SEMVER_PACKAGE_ALIAS}:test2"}
  1145. response = self.do_request(query)
  1146. assert response.status_code == 200, response.content
  1147. assert {r["id"] for r in response.data["data"]} == {
  1148. release_2_e_1,
  1149. }
  1150. def test_semver_build(self):
  1151. release_1 = self.create_release(version="test@1.2.3+123")
  1152. release_2 = self.create_release(version="test2@1.2.4+124")
  1153. release_1_e_1 = self.store_event(
  1154. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  1155. project_id=self.project.id,
  1156. ).event_id
  1157. release_1_e_2 = self.store_event(
  1158. data={"release": release_1.version, "timestamp": self.ten_mins_ago},
  1159. project_id=self.project.id,
  1160. ).event_id
  1161. release_2_e_1 = self.store_event(
  1162. data={"release": release_2.version, "timestamp": self.ten_mins_ago},
  1163. project_id=self.project.id,
  1164. ).event_id
  1165. query = {"field": ["id"], "query": f"{constants.SEMVER_BUILD_ALIAS}:123"}
  1166. response = self.do_request(query)
  1167. assert response.status_code == 200, response.content
  1168. assert {r["id"] for r in response.data["data"]} == {
  1169. release_1_e_1,
  1170. release_1_e_2,
  1171. }
  1172. query = {"field": ["id"], "query": f"{constants.SEMVER_BUILD_ALIAS}:124"}
  1173. response = self.do_request(query)
  1174. assert response.status_code == 200, response.content
  1175. assert {r["id"] for r in response.data["data"]} == {
  1176. release_2_e_1,
  1177. }
  1178. query = {"field": ["id"], "query": f"!{constants.SEMVER_BUILD_ALIAS}:124"}
  1179. response = self.do_request(query)
  1180. assert response.status_code == 200, response.content
  1181. assert {r["id"] for r in response.data["data"]} == {
  1182. release_1_e_1,
  1183. release_1_e_2,
  1184. }
  1185. def test_aliased_fields(self):
  1186. event1 = self.store_event(
  1187. data={
  1188. "event_id": "a" * 32,
  1189. "timestamp": self.ten_mins_ago,
  1190. "fingerprint": ["group_1"],
  1191. "user": {"email": "foo@example.com"},
  1192. },
  1193. project_id=self.project.id,
  1194. )
  1195. event2 = self.store_event(
  1196. data={
  1197. "event_id": "b" * 32,
  1198. "timestamp": self.ten_mins_ago,
  1199. "fingerprint": ["group_2"],
  1200. "user": {"email": "foo@example.com"},
  1201. },
  1202. project_id=self.project.id,
  1203. )
  1204. self.store_event(
  1205. data={
  1206. "event_id": "c" * 32,
  1207. "timestamp": self.ten_mins_ago,
  1208. "fingerprint": ["group_2"],
  1209. "user": {"email": "bar@example.com"},
  1210. },
  1211. project_id=self.project.id,
  1212. )
  1213. query = {"field": ["issue.id", "count(id)", "count_unique(user)"], "orderby": "issue.id"}
  1214. response = self.do_request(query)
  1215. assert response.status_code == 200, response.content
  1216. assert len(response.data["data"]) == 2
  1217. data = response.data["data"]
  1218. assert data[0]["issue.id"] == event1.group_id
  1219. assert data[0]["count(id)"] == 1
  1220. assert data[0]["count_unique(user)"] == 1
  1221. assert "projectid" not in data[0]
  1222. assert "project.id" not in data[0]
  1223. assert data[1]["issue.id"] == event2.group_id
  1224. assert data[1]["count(id)"] == 2
  1225. assert data[1]["count_unique(user)"] == 2
  1226. def test_aggregate_field_with_dotted_param(self):
  1227. event1 = self.store_event(
  1228. data={
  1229. "event_id": "a" * 32,
  1230. "timestamp": self.ten_mins_ago,
  1231. "fingerprint": ["group_1"],
  1232. "user": {"id": "123", "email": "foo@example.com"},
  1233. },
  1234. project_id=self.project.id,
  1235. )
  1236. event2 = self.store_event(
  1237. data={
  1238. "event_id": "b" * 32,
  1239. "timestamp": self.ten_mins_ago,
  1240. "fingerprint": ["group_2"],
  1241. "user": {"id": "123", "email": "foo@example.com"},
  1242. },
  1243. project_id=self.project.id,
  1244. )
  1245. self.store_event(
  1246. data={
  1247. "event_id": "c" * 32,
  1248. "timestamp": self.ten_mins_ago,
  1249. "fingerprint": ["group_2"],
  1250. "user": {"id": "456", "email": "bar@example.com"},
  1251. },
  1252. project_id=self.project.id,
  1253. )
  1254. query = {
  1255. "field": ["issue.id", "issue_title", "count(id)", "count_unique(user.email)"],
  1256. "orderby": "issue.id",
  1257. }
  1258. response = self.do_request(query)
  1259. assert response.status_code == 200, response.content
  1260. assert len(response.data["data"]) == 2
  1261. data = response.data["data"]
  1262. assert data[0]["issue.id"] == event1.group_id
  1263. assert data[0]["count(id)"] == 1
  1264. assert data[0]["count_unique(user.email)"] == 1
  1265. assert "projectid" not in data[0]
  1266. assert "project.id" not in data[0]
  1267. assert data[1]["issue.id"] == event2.group_id
  1268. assert data[1]["count(id)"] == 2
  1269. assert data[1]["count_unique(user.email)"] == 2
  1270. def test_failure_rate_alias_field(self):
  1271. data = self.transaction_data.copy()
  1272. data["transaction"] = "/failure_rate/success"
  1273. self.store_event(data, project_id=self.project.id)
  1274. data = self.transaction_data.copy()
  1275. data["transaction"] = "/failure_rate/unknown"
  1276. data["contexts"]["trace"]["status"] = "unknown_error"
  1277. self.store_event(data, project_id=self.project.id)
  1278. for i in range(6):
  1279. data = self.transaction_data.copy()
  1280. data["transaction"] = f"/failure_rate/{i}"
  1281. data["contexts"]["trace"]["status"] = "unauthenticated"
  1282. self.store_event(data, project_id=self.project.id)
  1283. query = {"field": ["failure_rate()"], "query": "event.type:transaction"}
  1284. response = self.do_request(query)
  1285. assert response.status_code == 200, response.content
  1286. assert len(response.data["data"]) == 1
  1287. data = response.data["data"]
  1288. assert data[0]["failure_rate()"] == 0.75
  1289. def test_count_miserable_alias_field(self):
  1290. events = [
  1291. ("one", 300),
  1292. ("one", 300),
  1293. ("two", 3000),
  1294. ("two", 3000),
  1295. ("three", 300),
  1296. ("three", 3000),
  1297. ]
  1298. for idx, event in enumerate(events):
  1299. data = self.load_data(
  1300. timestamp=before_now(minutes=(10 + idx)),
  1301. duration=timedelta(milliseconds=event[1]),
  1302. )
  1303. data["event_id"] = f"{idx}" * 32
  1304. data["transaction"] = f"/count_miserable/horribilis/{idx}"
  1305. data["user"] = {"email": f"{event[0]}@example.com"}
  1306. self.store_event(data, project_id=self.project.id)
  1307. query = {"field": ["count_miserable(user, 300)"], "query": "event.type:transaction"}
  1308. response = self.do_request(query)
  1309. assert response.status_code == 200, response.content
  1310. assert len(response.data["data"]) == 1
  1311. data = response.data["data"]
  1312. assert data[0]["count_miserable(user, 300)"] == 2
  1313. @mock.patch(
  1314. "sentry.search.events.fields.MAX_QUERYABLE_TRANSACTION_THRESHOLDS",
  1315. MAX_QUERYABLE_TRANSACTION_THRESHOLDS,
  1316. )
  1317. @mock.patch(
  1318. "sentry.search.events.datasets.discover.MAX_QUERYABLE_TRANSACTION_THRESHOLDS",
  1319. MAX_QUERYABLE_TRANSACTION_THRESHOLDS,
  1320. )
  1321. def test_too_many_transaction_thresholds(self):
  1322. project_transaction_thresholds = []
  1323. project_ids = []
  1324. for i in range(MAX_QUERYABLE_TRANSACTION_THRESHOLDS + 1):
  1325. project = self.create_project(name=f"bulk_txn_{i}")
  1326. project_ids.append(project.id)
  1327. project_transaction_thresholds.append(
  1328. ProjectTransactionThreshold(
  1329. organization=self.organization,
  1330. project=project,
  1331. threshold=400,
  1332. metric=TransactionMetric.LCP.value,
  1333. )
  1334. )
  1335. ProjectTransactionThreshold.objects.bulk_create(project_transaction_thresholds)
  1336. query = {
  1337. "field": [
  1338. "transaction",
  1339. "count_miserable(user)",
  1340. ],
  1341. "query": "event.type:transaction",
  1342. "project": project_ids,
  1343. }
  1344. response = self.do_request(
  1345. query,
  1346. features={
  1347. "organizations:discover-basic": True,
  1348. "organizations:global-views": True,
  1349. },
  1350. )
  1351. assert response.status_code == 400
  1352. assert (
  1353. response.data["detail"]
  1354. == "Exceeded 1 configured transaction thresholds limit, try with fewer Projects."
  1355. )
  1356. def test_count_miserable_new_alias_field(self):
  1357. ProjectTransactionThreshold.objects.create(
  1358. project=self.project,
  1359. organization=self.project.organization,
  1360. threshold=400,
  1361. metric=TransactionMetric.DURATION.value,
  1362. )
  1363. events = [
  1364. ("one", 400),
  1365. ("one", 400),
  1366. ("two", 3000),
  1367. ("two", 3000),
  1368. ("three", 300),
  1369. ("three", 3000),
  1370. ]
  1371. for idx, event in enumerate(events):
  1372. data = self.load_data(
  1373. timestamp=before_now(minutes=(10 + idx)),
  1374. duration=timedelta(milliseconds=event[1]),
  1375. )
  1376. data["event_id"] = f"{idx}" * 32
  1377. data["transaction"] = f"/count_miserable/horribilis/{event[0]}"
  1378. data["user"] = {"email": f"{idx}@example.com"}
  1379. self.store_event(data, project_id=self.project.id)
  1380. query = {
  1381. "field": [
  1382. "transaction",
  1383. "count_miserable(user)",
  1384. ],
  1385. "query": "event.type:transaction",
  1386. "project": [self.project.id],
  1387. "sort": "count_miserable_user",
  1388. }
  1389. response = self.do_request(
  1390. query,
  1391. )
  1392. assert response.status_code == 200, response.content
  1393. assert len(response.data["data"]) == 3
  1394. data = response.data["data"]
  1395. assert data[0]["count_miserable(user)"] == 0
  1396. assert data[1]["count_miserable(user)"] == 1
  1397. assert data[2]["count_miserable(user)"] == 2
  1398. query["query"] = "event.type:transaction count_miserable(user):>0"
  1399. response = self.do_request(
  1400. query,
  1401. )
  1402. assert response.status_code == 200, response.content
  1403. assert len(response.data["data"]) == 2
  1404. data = response.data["data"]
  1405. assert abs(data[0]["count_miserable(user)"]) == 1
  1406. assert abs(data[1]["count_miserable(user)"]) == 2
  1407. def test_user_misery_denominator(self):
  1408. """This is to test against a bug where the denominator of misery(total unique users) was wrong
  1409. This is because the total unique users for a LCP misery should only count users that have had a txn with lcp,
  1410. and not count all transactions (ie. uniq_if(transaction has lcp) not just uniq())
  1411. """
  1412. ProjectTransactionThreshold.objects.create(
  1413. project=self.project,
  1414. organization=self.project.organization,
  1415. threshold=600,
  1416. metric=TransactionMetric.LCP.value,
  1417. )
  1418. lcps = [
  1419. 400,
  1420. 400,
  1421. 300,
  1422. 3000,
  1423. 3000,
  1424. 3000,
  1425. ]
  1426. for idx, lcp in enumerate(lcps):
  1427. data = self.load_data(
  1428. timestamp=before_now(minutes=(10 + idx)),
  1429. )
  1430. data["event_id"] = f"{idx}" * 32
  1431. data["transaction"] = "/misery/new/"
  1432. data["user"] = {"email": f"{idx}@example.com"}
  1433. data["measurements"] = {
  1434. "lcp": {"value": lcp},
  1435. }
  1436. self.store_event(data, project_id=self.project.id)
  1437. # Shouldn't count towards misery
  1438. data = self.load_data(timestamp=before_now(minutes=10), duration=timedelta(milliseconds=0))
  1439. data["transaction"] = "/misery/new/"
  1440. data["user"] = {"email": "7@example.com"}
  1441. data["measurements"] = {}
  1442. self.store_event(data, project_id=self.project.id)
  1443. query = {
  1444. "field": [
  1445. "transaction",
  1446. "user_misery()",
  1447. ],
  1448. "query": "event.type:transaction",
  1449. "project": [self.project.id],
  1450. "sort": "-user_misery",
  1451. }
  1452. response = self.do_request(
  1453. query,
  1454. )
  1455. assert response.status_code == 200, response.content
  1456. assert len(response.data["data"]) == 1
  1457. data = response.data["data"]
  1458. # (3 frustrated + 5.8875) / (6 + 117.75)
  1459. assert abs(data[0]["user_misery()"] - 0.071818) < 0.0001
  1460. def test_user_misery_alias_field(self):
  1461. events = [
  1462. ("one", 300),
  1463. ("one", 300),
  1464. ("two", 3000),
  1465. ("two", 3000),
  1466. ("three", 300),
  1467. ("three", 3000),
  1468. ]
  1469. for idx, event in enumerate(events):
  1470. data = self.load_data(
  1471. timestamp=before_now(minutes=(10 + idx)),
  1472. duration=timedelta(milliseconds=event[1]),
  1473. )
  1474. data["event_id"] = f"{idx}" * 32
  1475. data["transaction"] = f"/user_misery/{idx}"
  1476. data["user"] = {"email": f"{event[0]}@example.com"}
  1477. self.store_event(data, project_id=self.project.id)
  1478. query = {"field": ["user_misery(300)"], "query": "event.type:transaction"}
  1479. response = self.do_request(query)
  1480. assert response.status_code == 200, response.content
  1481. assert len(response.data["data"]) == 1
  1482. data = response.data["data"]
  1483. assert abs(data[0]["user_misery(300)"] - 0.0653) < 0.0001
  1484. def test_apdex_denominator_correct(self):
  1485. """This is to test against a bug where the denominator of apdex(total count) was wrong
  1486. This is because the total_count for a LCP apdex should only count transactions that have lcp, and not count
  1487. all transactions (ie. count_if(transaction has lcp) not just count())
  1488. """
  1489. ProjectTransactionThreshold.objects.create(
  1490. project=self.project,
  1491. organization=self.project.organization,
  1492. threshold=600,
  1493. metric=TransactionMetric.LCP.value,
  1494. )
  1495. lcps = [
  1496. 400,
  1497. 400,
  1498. 300,
  1499. 800,
  1500. 3000,
  1501. 3000,
  1502. 3000,
  1503. ]
  1504. for idx, lcp in enumerate(lcps):
  1505. data = self.load_data(
  1506. timestamp=before_now(minutes=(10 + idx)),
  1507. )
  1508. data["event_id"] = f"{idx}" * 32
  1509. data["transaction"] = "/apdex/new/"
  1510. data["user"] = {"email": f"{idx}@example.com"}
  1511. data["measurements"] = {
  1512. "lcp": {"value": lcp},
  1513. }
  1514. self.store_event(data, project_id=self.project.id)
  1515. # Shouldn't count towards apdex
  1516. data = self.load_data(
  1517. timestamp=before_now(minutes=10),
  1518. duration=timedelta(milliseconds=0),
  1519. )
  1520. data["transaction"] = "/apdex/new/"
  1521. data["user"] = {"email": "7@example.com"}
  1522. data["measurements"] = {}
  1523. self.store_event(data, project_id=self.project.id)
  1524. query = {
  1525. "field": [
  1526. "transaction",
  1527. "apdex()",
  1528. ],
  1529. "query": "event.type:transaction",
  1530. "project": [self.project.id],
  1531. "sort": "-apdex",
  1532. }
  1533. response = self.do_request(
  1534. query,
  1535. )
  1536. assert response.status_code == 200, response.content
  1537. assert len(response.data["data"]) == 1
  1538. data = response.data["data"]
  1539. # 3 satisfied + 1 tolerated => 3.5/7
  1540. assert data[0]["apdex()"] == 0.5
  1541. def test_apdex_new_alias_field(self):
  1542. ProjectTransactionThreshold.objects.create(
  1543. project=self.project,
  1544. organization=self.project.organization,
  1545. threshold=400,
  1546. metric=TransactionMetric.DURATION.value,
  1547. )
  1548. events = [
  1549. ("one", 400),
  1550. ("one", 400),
  1551. ("two", 3000),
  1552. ("two", 3000),
  1553. ("three", 300),
  1554. ("three", 3000),
  1555. ]
  1556. for idx, event in enumerate(events):
  1557. data = self.load_data(
  1558. timestamp=before_now(minutes=(10 + idx)),
  1559. duration=timedelta(milliseconds=event[1]),
  1560. )
  1561. data["event_id"] = f"{idx}" * 32
  1562. data["transaction"] = f"/apdex/new/{event[0]}"
  1563. data["user"] = {"email": f"{idx}@example.com"}
  1564. self.store_event(data, project_id=self.project.id)
  1565. query = {
  1566. "field": [
  1567. "transaction",
  1568. "apdex()",
  1569. ],
  1570. "query": "event.type:transaction",
  1571. "project": [self.project.id],
  1572. "sort": "-apdex",
  1573. }
  1574. response = self.do_request(
  1575. query,
  1576. )
  1577. assert response.status_code == 200, response.content
  1578. assert len(response.data["data"]) == 3
  1579. data = response.data["data"]
  1580. assert data[0]["apdex()"] == 1.0
  1581. assert data[1]["apdex()"] == 0.5
  1582. assert data[2]["apdex()"] == 0.0
  1583. query["query"] = "event.type:transaction apdex():>0.50"
  1584. response = self.do_request(
  1585. query,
  1586. )
  1587. assert response.status_code == 200, response.content
  1588. assert len(response.data["data"]) == 1
  1589. data = response.data["data"]
  1590. assert data[0]["apdex()"] == 1.0
  1591. def test_user_misery_alias_field_with_project_threshold(self):
  1592. ProjectTransactionThreshold.objects.create(
  1593. project=self.project,
  1594. organization=self.project.organization,
  1595. threshold=400,
  1596. metric=TransactionMetric.DURATION.value,
  1597. )
  1598. events = [
  1599. ("one", 400),
  1600. ("one", 400),
  1601. ("two", 3000),
  1602. ("two", 3000),
  1603. ("three", 300),
  1604. ("three", 3000),
  1605. ]
  1606. for idx, event in enumerate(events):
  1607. data = self.load_data(
  1608. timestamp=before_now(minutes=(10 + idx)),
  1609. duration=timedelta(milliseconds=event[1]),
  1610. )
  1611. data["event_id"] = f"{idx}" * 32
  1612. data["transaction"] = f"/count_miserable/horribilis/{event[0]}"
  1613. data["user"] = {"email": f"{idx}@example.com"}
  1614. self.store_event(data, project_id=self.project.id)
  1615. query = {
  1616. "field": [
  1617. "transaction",
  1618. "user_misery()",
  1619. ],
  1620. "orderby": "user_misery()",
  1621. "query": "event.type:transaction",
  1622. "project": [self.project.id],
  1623. }
  1624. response = self.do_request(query)
  1625. assert response.status_code == 200, response.content
  1626. assert len(response.data["data"]) == 3
  1627. data = response.data["data"]
  1628. assert data[0]["user_misery()"] == pytest.approx(0.04916, rel=1e-3)
  1629. assert data[1]["user_misery()"] == pytest.approx(0.05751, rel=1e-3)
  1630. assert data[2]["user_misery()"] == pytest.approx(0.06586, rel=1e-3)
  1631. query["query"] = "event.type:transaction user_misery():>0.050"
  1632. response = self.do_request(
  1633. query,
  1634. )
  1635. assert response.status_code == 200, response.content
  1636. assert len(response.data["data"]) == 2
  1637. data = response.data["data"]
  1638. assert data[0]["user_misery()"] == pytest.approx(0.05751, rel=1e-3)
  1639. assert data[1]["user_misery()"] == pytest.approx(0.06586, rel=1e-3)
  1640. def test_user_misery_alias_field_with_transaction_threshold(self):
  1641. events = [
  1642. ("one", 300),
  1643. ("two", 300),
  1644. ("one", 3000),
  1645. ("two", 3000),
  1646. ("three", 400),
  1647. ("four", 4000),
  1648. ]
  1649. for idx, event in enumerate(events):
  1650. data = self.load_data(
  1651. timestamp=before_now(minutes=(10 + idx)),
  1652. duration=timedelta(milliseconds=event[1]),
  1653. )
  1654. data["event_id"] = f"{idx}" * 32
  1655. data["transaction"] = f"/count_miserable/horribilis/{idx}"
  1656. data["user"] = {"email": f"{event[0]}@example.com"}
  1657. self.store_event(data, project_id=self.project.id)
  1658. if idx % 2:
  1659. ProjectTransactionThresholdOverride.objects.create(
  1660. transaction=f"/count_miserable/horribilis/{idx}",
  1661. project=self.project,
  1662. organization=self.project.organization,
  1663. threshold=100 * idx,
  1664. metric=TransactionMetric.DURATION.value,
  1665. )
  1666. query = {
  1667. "field": [
  1668. "transaction",
  1669. "user_misery()",
  1670. ],
  1671. "query": "event.type:transaction",
  1672. "orderby": "transaction",
  1673. "project": [self.project.id],
  1674. }
  1675. response = self.do_request(
  1676. query,
  1677. )
  1678. assert response.status_code == 200, response.content
  1679. expected = [
  1680. ("/count_miserable/horribilis/0", ["duration", 300], 0.049578),
  1681. ("/count_miserable/horribilis/1", ["duration", 100], 0.049578),
  1682. ("/count_miserable/horribilis/2", ["duration", 300], 0.058),
  1683. ("/count_miserable/horribilis/3", ["duration", 300], 0.058),
  1684. ("/count_miserable/horribilis/4", ["duration", 300], 0.049578),
  1685. ("/count_miserable/horribilis/5", ["duration", 500], 0.058),
  1686. ]
  1687. assert len(response.data["data"]) == 6
  1688. data = response.data["data"]
  1689. for i, record in enumerate(expected):
  1690. name, threshold_config, misery = record
  1691. assert data[i]["transaction"] == name
  1692. assert data[i]["project_threshold_config"] == threshold_config
  1693. assert data[i]["user_misery()"] == pytest.approx(misery, rel=1e-3)
  1694. query["query"] = "event.type:transaction user_misery():>0.050"
  1695. response = self.do_request(
  1696. query,
  1697. )
  1698. assert response.status_code == 200, response.content
  1699. assert len(response.data["data"]) == 3
  1700. data = response.data["data"]
  1701. assert data[0]["user_misery()"] == pytest.approx(0.058, rel=1e-3)
  1702. assert data[1]["user_misery()"] == pytest.approx(0.058, rel=1e-3)
  1703. assert data[2]["user_misery()"] == pytest.approx(0.058, rel=1e-3)
  1704. def test_user_misery_alias_field_with_transaction_threshold_and_project_threshold(self):
  1705. project = self.create_project()
  1706. ProjectTransactionThreshold.objects.create(
  1707. project=project,
  1708. organization=project.organization,
  1709. threshold=100,
  1710. metric=TransactionMetric.DURATION.value,
  1711. )
  1712. events = [
  1713. ("one", 300),
  1714. ("two", 300),
  1715. ("one", 3000),
  1716. ("two", 3000),
  1717. ("three", 400),
  1718. ("four", 4000),
  1719. ]
  1720. for idx, event in enumerate(events):
  1721. data = self.load_data(
  1722. timestamp=before_now(minutes=(10 + idx)),
  1723. duration=timedelta(milliseconds=event[1]),
  1724. )
  1725. data["event_id"] = f"{idx}" * 32
  1726. data["transaction"] = f"/count_miserable/horribilis/{idx}"
  1727. data["user"] = {"email": f"{event[0]}@example.com"}
  1728. self.store_event(data, project_id=project.id)
  1729. if idx % 2:
  1730. ProjectTransactionThresholdOverride.objects.create(
  1731. transaction=f"/count_miserable/horribilis/{idx}",
  1732. project=project,
  1733. organization=project.organization,
  1734. threshold=100 * idx,
  1735. metric=TransactionMetric.DURATION.value,
  1736. )
  1737. project2 = self.create_project()
  1738. data = self.load_data(timestamp=before_now(minutes=1))
  1739. data["transaction"] = "/count_miserable/horribilis/project2"
  1740. data["user"] = {"email": "project2@example.com"}
  1741. self.store_event(data, project_id=project2.id)
  1742. query = {
  1743. "field": [
  1744. "transaction",
  1745. "user_misery()",
  1746. ],
  1747. "query": "event.type:transaction",
  1748. "orderby": "transaction",
  1749. "project": [project.id, project2.id],
  1750. }
  1751. response = self.do_request(
  1752. query,
  1753. features={
  1754. "organizations:discover-basic": True,
  1755. "organizations:global-views": True,
  1756. },
  1757. )
  1758. assert response.status_code == 200, response.content
  1759. expected = [
  1760. (
  1761. "/count_miserable/horribilis/0",
  1762. ["duration", 100],
  1763. 0.049578,
  1764. ), # Uses project threshold
  1765. ("/count_miserable/horribilis/1", ["duration", 100], 0.049578), # Uses txn threshold
  1766. ("/count_miserable/horribilis/2", ["duration", 100], 0.058), # Uses project threshold
  1767. ("/count_miserable/horribilis/3", ["duration", 300], 0.058), # Uses txn threshold
  1768. (
  1769. "/count_miserable/horribilis/4",
  1770. ["duration", 100],
  1771. 0.049578,
  1772. ), # Uses project threshold
  1773. ("/count_miserable/horribilis/5", ["duration", 500], 0.058), # Uses txn threshold
  1774. ("/count_miserable/horribilis/project2", ["duration", 300], 0.058), # Uses fallback
  1775. ]
  1776. assert len(response.data["data"]) == 7
  1777. data = response.data["data"]
  1778. for i, record in enumerate(expected):
  1779. name, threshold_config, misery = record
  1780. assert data[i]["transaction"] == name
  1781. assert data[i]["project_threshold_config"] == threshold_config
  1782. assert data[i]["user_misery()"] == pytest.approx(misery, rel=1e-3)
  1783. query["query"] = "event.type:transaction user_misery():>0.050"
  1784. response = self.do_request(
  1785. query,
  1786. features={
  1787. "organizations:discover-basic": True,
  1788. "organizations:global-views": True,
  1789. },
  1790. )
  1791. assert response.status_code == 200, response.content
  1792. assert len(response.data["data"]) == 4
  1793. def test_aggregation(self):
  1794. self.store_event(
  1795. data={
  1796. "event_id": "a" * 32,
  1797. "timestamp": self.ten_mins_ago,
  1798. "fingerprint": ["group_1"],
  1799. "user": {"email": "foo@example.com"},
  1800. "environment": "prod",
  1801. "tags": {"sub_customer.is-Enterprise-42": "1"},
  1802. },
  1803. project_id=self.project.id,
  1804. )
  1805. self.store_event(
  1806. data={
  1807. "event_id": "b" * 32,
  1808. "timestamp": self.ten_mins_ago,
  1809. "fingerprint": ["group_2"],
  1810. "user": {"email": "foo@example.com"},
  1811. "environment": "staging",
  1812. "tags": {"sub_customer.is-Enterprise-42": "1"},
  1813. },
  1814. project_id=self.project.id,
  1815. )
  1816. self.store_event(
  1817. data={
  1818. "event_id": "c" * 32,
  1819. "timestamp": self.ten_mins_ago,
  1820. "fingerprint": ["group_2"],
  1821. "user": {"email": "foo@example.com"},
  1822. "environment": "prod",
  1823. "tags": {"sub_customer.is-Enterprise-42": "0"},
  1824. },
  1825. project_id=self.project.id,
  1826. )
  1827. self.store_event(
  1828. data={
  1829. "event_id": "d" * 32,
  1830. "timestamp": self.ten_mins_ago,
  1831. "fingerprint": ["group_2"],
  1832. "user": {"email": "foo@example.com"},
  1833. "environment": "prod",
  1834. "tags": {"sub_customer.is-Enterprise-42": "1"},
  1835. },
  1836. project_id=self.project.id,
  1837. )
  1838. query = {
  1839. "field": ["sub_customer.is-Enterprise-42", "count(sub_customer.is-Enterprise-42)"],
  1840. "orderby": "sub_customer.is-Enterprise-42",
  1841. }
  1842. response = self.do_request(query)
  1843. assert response.status_code == 200, response.content
  1844. assert len(response.data["data"]) == 2
  1845. data = response.data["data"]
  1846. assert data[0]["count(sub_customer.is-Enterprise-42)"] == 1
  1847. assert data[1]["count(sub_customer.is-Enterprise-42)"] == 3
  1848. def test_aggregation_comparison(self):
  1849. self.store_event(
  1850. data={
  1851. "event_id": "a" * 32,
  1852. "timestamp": self.ten_mins_ago,
  1853. "fingerprint": ["group_1"],
  1854. "user": {"email": "foo@example.com"},
  1855. },
  1856. project_id=self.project.id,
  1857. )
  1858. event = self.store_event(
  1859. data={
  1860. "event_id": "b" * 32,
  1861. "timestamp": self.ten_mins_ago,
  1862. "fingerprint": ["group_2"],
  1863. "user": {"email": "foo@example.com"},
  1864. },
  1865. project_id=self.project.id,
  1866. )
  1867. self.store_event(
  1868. data={
  1869. "event_id": "c" * 32,
  1870. "timestamp": self.ten_mins_ago,
  1871. "fingerprint": ["group_2"],
  1872. "user": {"email": "bar@example.com"},
  1873. },
  1874. project_id=self.project.id,
  1875. )
  1876. self.store_event(
  1877. data={
  1878. "event_id": "d" * 32,
  1879. "timestamp": self.ten_mins_ago,
  1880. "fingerprint": ["group_3"],
  1881. "user": {"email": "bar@example.com"},
  1882. },
  1883. project_id=self.project.id,
  1884. )
  1885. self.store_event(
  1886. data={
  1887. "event_id": "e" * 32,
  1888. "timestamp": self.ten_mins_ago,
  1889. "fingerprint": ["group_3"],
  1890. "user": {"email": "bar@example.com"},
  1891. },
  1892. project_id=self.project.id,
  1893. )
  1894. query = {
  1895. "field": ["issue.id", "count(id)", "count_unique(user)"],
  1896. "query": "count(id):>1 count_unique(user):>1",
  1897. "orderby": "issue.id",
  1898. }
  1899. response = self.do_request(query)
  1900. assert response.status_code == 200, response.content
  1901. assert len(response.data["data"]) == 1
  1902. data = response.data["data"]
  1903. assert data[0]["issue.id"] == event.group_id
  1904. assert data[0]["count(id)"] == 2
  1905. assert data[0]["count_unique(user)"] == 2
  1906. def test_aggregation_alias_comparison(self):
  1907. data = self.load_data(
  1908. timestamp=before_now(minutes=10),
  1909. duration=timedelta(seconds=5),
  1910. )
  1911. data["transaction"] = "/aggregates/1"
  1912. self.store_event(data, project_id=self.project.id)
  1913. data = self.load_data(
  1914. timestamp=before_now(minutes=10),
  1915. duration=timedelta(seconds=3),
  1916. )
  1917. data["transaction"] = "/aggregates/2"
  1918. event = self.store_event(data, project_id=self.project.id)
  1919. query = {
  1920. "field": ["transaction", "p95()"],
  1921. "query": "event.type:transaction p95():<4000",
  1922. "orderby": ["transaction"],
  1923. }
  1924. response = self.do_request(query)
  1925. assert response.status_code == 200, response.content
  1926. assert len(response.data["data"]) == 1
  1927. data = response.data["data"]
  1928. assert data[0]["transaction"] == event.transaction
  1929. assert data[0]["p95()"] == 3000
  1930. def test_auto_aggregations(self):
  1931. data = self.load_data(
  1932. timestamp=before_now(minutes=10),
  1933. duration=timedelta(seconds=5),
  1934. )
  1935. data["transaction"] = "/aggregates/1"
  1936. self.store_event(data, project_id=self.project.id)
  1937. data = self.load_data(
  1938. timestamp=before_now(minutes=10),
  1939. duration=timedelta(seconds=3),
  1940. )
  1941. data["transaction"] = "/aggregates/2"
  1942. event = self.store_event(data, project_id=self.project.id)
  1943. query = {
  1944. "field": ["transaction", "p75()"],
  1945. "query": "event.type:transaction p95():<4000",
  1946. "orderby": ["transaction"],
  1947. }
  1948. response = self.do_request(query)
  1949. assert response.status_code == 200, response.content
  1950. assert len(response.data["data"]) == 1
  1951. data = response.data["data"]
  1952. assert data[0]["transaction"] == event.transaction
  1953. query = {
  1954. "field": ["transaction"],
  1955. "query": "event.type:transaction p95():<4000",
  1956. "orderby": ["transaction"],
  1957. }
  1958. response = self.do_request(query)
  1959. assert response.status_code == 400, response.content
  1960. def test_aggregation_comparison_with_conditions(self):
  1961. self.store_event(
  1962. data={
  1963. "event_id": "a" * 32,
  1964. "timestamp": self.ten_mins_ago,
  1965. "fingerprint": ["group_1"],
  1966. "user": {"email": "foo@example.com"},
  1967. "environment": "prod",
  1968. },
  1969. project_id=self.project.id,
  1970. )
  1971. self.store_event(
  1972. data={
  1973. "event_id": "b" * 32,
  1974. "timestamp": self.ten_mins_ago,
  1975. "fingerprint": ["group_2"],
  1976. "user": {"email": "foo@example.com"},
  1977. "environment": "staging",
  1978. },
  1979. project_id=self.project.id,
  1980. )
  1981. event = self.store_event(
  1982. data={
  1983. "event_id": "c" * 32,
  1984. "timestamp": self.ten_mins_ago,
  1985. "fingerprint": ["group_2"],
  1986. "user": {"email": "foo@example.com"},
  1987. "environment": "prod",
  1988. },
  1989. project_id=self.project.id,
  1990. )
  1991. self.store_event(
  1992. data={
  1993. "event_id": "d" * 32,
  1994. "timestamp": self.ten_mins_ago,
  1995. "fingerprint": ["group_2"],
  1996. "user": {"email": "foo@example.com"},
  1997. "environment": "prod",
  1998. },
  1999. project_id=self.project.id,
  2000. )
  2001. query = {
  2002. "field": ["issue.id", "count(id)"],
  2003. "query": "count(id):>1 user.email:foo@example.com environment:prod",
  2004. "orderby": "issue.id",
  2005. }
  2006. response = self.do_request(query)
  2007. assert response.status_code == 200, response.content
  2008. assert len(response.data["data"]) == 1
  2009. data = response.data["data"]
  2010. assert data[0]["issue.id"] == event.group_id
  2011. assert data[0]["count(id)"] == 2
  2012. def test_aggregation_date_comparison_with_conditions(self):
  2013. event = self.store_event(
  2014. data={
  2015. "event_id": "a" * 32,
  2016. "timestamp": self.ten_mins_ago,
  2017. "fingerprint": ["group_1"],
  2018. "user": {"email": "foo@example.com"},
  2019. "environment": "prod",
  2020. },
  2021. project_id=self.project.id,
  2022. )
  2023. self.store_event(
  2024. data={
  2025. "event_id": "b" * 32,
  2026. "timestamp": self.ten_mins_ago,
  2027. "fingerprint": ["group_2"],
  2028. "user": {"email": "foo@example.com"},
  2029. "environment": "staging",
  2030. },
  2031. project_id=self.project.id,
  2032. )
  2033. self.store_event(
  2034. data={
  2035. "event_id": "c" * 32,
  2036. "timestamp": self.ten_mins_ago,
  2037. "fingerprint": ["group_2"],
  2038. "user": {"email": "foo@example.com"},
  2039. "environment": "prod",
  2040. },
  2041. project_id=self.project.id,
  2042. )
  2043. self.store_event(
  2044. data={
  2045. "event_id": "d" * 32,
  2046. "timestamp": self.ten_mins_ago,
  2047. "fingerprint": ["group_2"],
  2048. "user": {"email": "foo@example.com"},
  2049. "environment": "prod",
  2050. },
  2051. project_id=self.project.id,
  2052. )
  2053. query = {
  2054. "field": ["issue.id", "max(timestamp)"],
  2055. "query": "max(timestamp):>1 user.email:foo@example.com environment:prod",
  2056. "orderby": "issue.id",
  2057. }
  2058. response = self.do_request(query)
  2059. assert response.status_code == 200, response.content
  2060. assert len(response.data["data"]) == 2
  2061. assert response.data["meta"]["fields"]["max(timestamp)"] == "date"
  2062. data = response.data["data"]
  2063. assert data[0]["issue.id"] == event.group_id
  2064. def test_percentile_function(self):
  2065. data = self.load_data(
  2066. timestamp=before_now(minutes=10),
  2067. duration=timedelta(seconds=5),
  2068. )
  2069. data["transaction"] = "/aggregates/1"
  2070. event1 = self.store_event(data, project_id=self.project.id)
  2071. data = self.load_data(
  2072. timestamp=before_now(minutes=10),
  2073. duration=timedelta(seconds=3),
  2074. )
  2075. data["transaction"] = "/aggregates/2"
  2076. event2 = self.store_event(data, project_id=self.project.id)
  2077. query = {
  2078. "field": ["transaction", "percentile(transaction.duration, 0.95)"],
  2079. "query": "event.type:transaction",
  2080. "orderby": ["transaction"],
  2081. }
  2082. response = self.do_request(query)
  2083. assert response.status_code == 200, response.content
  2084. assert len(response.data["data"]) == 2
  2085. data = response.data["data"]
  2086. assert data[0]["transaction"] == event1.transaction
  2087. assert data[0]["percentile(transaction.duration, 0.95)"] == 5000
  2088. assert data[1]["transaction"] == event2.transaction
  2089. assert data[1]["percentile(transaction.duration, 0.95)"] == 3000
  2090. def test_percentile_function_as_condition(self):
  2091. data = self.load_data(
  2092. timestamp=before_now(minutes=10),
  2093. duration=timedelta(seconds=5),
  2094. )
  2095. data["transaction"] = "/aggregates/1"
  2096. event1 = self.store_event(data, project_id=self.project.id)
  2097. data = self.load_data(
  2098. timestamp=before_now(minutes=10),
  2099. duration=timedelta(seconds=3),
  2100. )
  2101. data["transaction"] = "/aggregates/2"
  2102. self.store_event(data, project_id=self.project.id)
  2103. query = {
  2104. "field": ["transaction", "percentile(transaction.duration, 0.95)"],
  2105. "query": "event.type:transaction percentile(transaction.duration, 0.95):>4000",
  2106. "orderby": ["transaction"],
  2107. }
  2108. response = self.do_request(query)
  2109. assert response.status_code == 200, response.content
  2110. assert len(response.data["data"]) == 1
  2111. data = response.data["data"]
  2112. assert data[0]["transaction"] == event1.transaction
  2113. assert data[0]["percentile(transaction.duration, 0.95)"] == 5000
  2114. def test_epm_function(self):
  2115. data = self.load_data(
  2116. timestamp=before_now(minutes=10),
  2117. duration=timedelta(seconds=5),
  2118. )
  2119. data["transaction"] = "/aggregates/1"
  2120. event1 = self.store_event(data, project_id=self.project.id)
  2121. data = self.load_data(
  2122. timestamp=before_now(minutes=10),
  2123. duration=timedelta(seconds=3),
  2124. )
  2125. data["transaction"] = "/aggregates/2"
  2126. event2 = self.store_event(data, project_id=self.project.id)
  2127. query = {
  2128. "field": ["transaction", "epm()"],
  2129. "query": "event.type:transaction",
  2130. "orderby": ["transaction"],
  2131. "start": iso_format(before_now(minutes=11)),
  2132. "end": iso_format(before_now(minutes=9)),
  2133. }
  2134. response = self.do_request(query)
  2135. assert response.status_code == 200, response.content
  2136. assert len(response.data["data"]) == 2
  2137. data = response.data["data"]
  2138. assert data[0]["transaction"] == event1.transaction
  2139. assert data[0]["epm()"] == 0.5
  2140. assert data[1]["transaction"] == event2.transaction
  2141. assert data[1]["epm()"] == 0.5
  2142. def test_nonexistent_fields(self):
  2143. self.store_event(
  2144. data={
  2145. "event_id": "a" * 32,
  2146. "message": "how to make fast",
  2147. "timestamp": self.ten_mins_ago,
  2148. },
  2149. project_id=self.project.id,
  2150. )
  2151. query = {"field": ["issue_world.id"]}
  2152. response = self.do_request(query)
  2153. assert response.status_code == 200, response.content
  2154. assert response.data["data"][0]["issue_world.id"] == ""
  2155. def test_no_requested_fields_or_grouping(self):
  2156. self.store_event(
  2157. data={
  2158. "event_id": "a" * 32,
  2159. "message": "how to make fast",
  2160. "timestamp": self.ten_mins_ago,
  2161. },
  2162. project_id=self.project.id,
  2163. )
  2164. query = {"query": "test"}
  2165. response = self.do_request(query)
  2166. assert response.status_code == 400, response.content
  2167. assert response.data["detail"] == "No columns selected"
  2168. def test_condition_on_aggregate_misses(self):
  2169. self.store_event(
  2170. data={
  2171. "event_id": "c" * 32,
  2172. "timestamp": self.ten_mins_ago,
  2173. "fingerprint": ["group_2"],
  2174. "user": {"email": "bar@example.com"},
  2175. },
  2176. project_id=self.project.id,
  2177. )
  2178. query = {"field": ["issue.id"], "query": "event_count:>0", "orderby": "issue.id"}
  2179. response = self.do_request(query)
  2180. assert response.status_code == 200, response.content
  2181. assert len(response.data["data"]) == 0
  2182. def test_next_prev_link_headers(self):
  2183. events = [("a", "group_1"), ("b", "group_2"), ("c", "group_2"), ("d", "group_2")]
  2184. for e in events:
  2185. self.store_event(
  2186. data={
  2187. "event_id": e[0] * 32,
  2188. "timestamp": self.ten_mins_ago,
  2189. "fingerprint": [e[1]],
  2190. "user": {"email": "foo@example.com"},
  2191. "tags": {"language": "C++"},
  2192. },
  2193. project_id=self.project.id,
  2194. )
  2195. query = {
  2196. "field": ["count(id)", "issue.id", "context.key"],
  2197. "sort": "-count_id",
  2198. "query": "language:C++",
  2199. }
  2200. response = self.do_request(query)
  2201. assert response.status_code == 200, response.content
  2202. links = parse_link_header(response["Link"])
  2203. for link in links:
  2204. assert "field=issue.id" in link
  2205. assert "field=count%28id%29" in link
  2206. assert "field=context.key" in link
  2207. assert "sort=-count_id" in link
  2208. assert "query=language%3AC%2B%2B" in link
  2209. assert len(response.data["data"]) == 2
  2210. data = response.data["data"]
  2211. assert data[0]["count(id)"] == 3
  2212. assert data[1]["count(id)"] == 1
  2213. def test_empty_count_query(self):
  2214. event = self.store_event(
  2215. data={
  2216. "event_id": "a" * 32,
  2217. "timestamp": self.ten_mins_ago,
  2218. "fingerprint": ["1123581321"],
  2219. "user": {"email": "foo@example.com"},
  2220. "tags": {"language": "C++"},
  2221. },
  2222. project_id=self.project.id,
  2223. )
  2224. query = {
  2225. "field": ["count()"],
  2226. "query": f"issue.id:{event.group_id} timestamp:>{self.ten_mins_ago}",
  2227. "statsPeriod": "14d",
  2228. }
  2229. response = self.do_request(query)
  2230. assert response.status_code == 200, response.content
  2231. data = response.data["data"]
  2232. assert len(data) == 1
  2233. assert data[0]["count()"] == 0
  2234. def test_stack_wildcard_condition(self):
  2235. data = self.load_data(platform="javascript")
  2236. data["timestamp"] = self.ten_mins_ago
  2237. self.store_event(data=data, project_id=self.project.id)
  2238. query = {"field": ["stack.filename", "message"], "query": "stack.filename:*.js"}
  2239. response = self.do_request(query)
  2240. assert response.status_code == 200, response.content
  2241. assert len(response.data["data"]) == 1
  2242. assert response.data["meta"]["fields"]["message"] == "string"
  2243. def test_email_wildcard_condition(self):
  2244. data = self.load_data(platform="javascript")
  2245. data["timestamp"] = self.ten_mins_ago
  2246. self.store_event(data=data, project_id=self.project.id)
  2247. query = {"field": ["stack.filename", "message"], "query": "user.email:*@example.org"}
  2248. response = self.do_request(query)
  2249. assert response.status_code == 200, response.content
  2250. assert len(response.data["data"]) == 1
  2251. assert response.data["meta"]["fields"]["message"] == "string"
  2252. def test_release_wildcard_condition(self):
  2253. release = self.create_release(version="test@1.2.3+123")
  2254. self.store_event(
  2255. data={"release": release.version, "timestamp": self.ten_mins_ago},
  2256. project_id=self.project.id,
  2257. )
  2258. query = {"field": ["stack.filename", "release"], "query": "release:test*"}
  2259. response = self.do_request(query)
  2260. assert response.status_code == 200, response.content
  2261. assert len(response.data["data"]) == 1
  2262. assert response.data["data"][0]["release"] == release.version
  2263. def test_transaction_event_type(self):
  2264. self.store_event(data=self.transaction_data, project_id=self.project.id)
  2265. query = {
  2266. "field": ["transaction", "transaction.duration", "transaction.status"],
  2267. "query": "event.type:transaction",
  2268. }
  2269. response = self.do_request(query)
  2270. assert response.status_code == 200, response.content
  2271. assert len(response.data["data"]) == 1
  2272. assert response.data["meta"]["fields"]["transaction.duration"] == "duration"
  2273. assert response.data["meta"]["fields"]["transaction.status"] == "string"
  2274. assert response.data["meta"]["units"]["transaction.duration"] == "millisecond"
  2275. assert response.data["data"][0]["transaction.status"] == "ok"
  2276. def test_trace_columns(self):
  2277. self.store_event(data=self.transaction_data, project_id=self.project.id)
  2278. query = {"field": ["trace"], "query": "event.type:transaction"}
  2279. response = self.do_request(query)
  2280. assert response.status_code == 200, response.content
  2281. assert len(response.data["data"]) == 1
  2282. assert response.data["meta"]["fields"]["trace"] == "string"
  2283. assert (
  2284. response.data["data"][0]["trace"]
  2285. == self.transaction_data["contexts"]["trace"]["trace_id"]
  2286. )
  2287. def test_issue_in_columns(self):
  2288. project1 = self.create_project()
  2289. project2 = self.create_project()
  2290. event1 = self.store_event(
  2291. data={
  2292. "event_id": "a" * 32,
  2293. "transaction": "/example",
  2294. "message": "how to make fast",
  2295. "timestamp": self.ten_mins_ago,
  2296. "fingerprint": ["group_1"],
  2297. },
  2298. project_id=project1.id,
  2299. )
  2300. event2 = self.store_event(
  2301. data={
  2302. "event_id": "b" * 32,
  2303. "transaction": "/example",
  2304. "message": "how to make fast",
  2305. "timestamp": self.ten_mins_ago,
  2306. "fingerprint": ["group_1"],
  2307. },
  2308. project_id=project2.id,
  2309. )
  2310. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2311. query = {"field": ["id", "issue"], "orderby": ["id"]}
  2312. response = self.do_request(query, features=features)
  2313. assert response.status_code == 200, response.content
  2314. data = response.data["data"]
  2315. assert len(data) == 2
  2316. assert data[0]["id"] == event1.event_id
  2317. assert data[0]["issue.id"] == event1.group_id
  2318. assert data[0]["issue"] == event1.group.qualified_short_id
  2319. assert data[1]["id"] == event2.event_id
  2320. assert data[1]["issue.id"] == event2.group_id
  2321. assert data[1]["issue"] == event2.group.qualified_short_id
  2322. def test_issue_in_search_and_columns(self):
  2323. project1 = self.create_project()
  2324. project2 = self.create_project()
  2325. event1 = self.store_event(
  2326. data={
  2327. "event_id": "a" * 32,
  2328. "transaction": "/example",
  2329. "message": "how to make fast",
  2330. "timestamp": self.ten_mins_ago,
  2331. "fingerprint": ["group_1"],
  2332. },
  2333. project_id=project1.id,
  2334. )
  2335. self.store_event(
  2336. data={
  2337. "event_id": "b" * 32,
  2338. "transaction": "/example",
  2339. "message": "how to make fast",
  2340. "timestamp": self.ten_mins_ago,
  2341. "fingerprint": ["group_1"],
  2342. },
  2343. project_id=project2.id,
  2344. )
  2345. tests = [
  2346. ("issue", "issue:%s" % event1.group.qualified_short_id),
  2347. ("issue.id", "issue:%s" % event1.group.qualified_short_id),
  2348. ("issue", "issue.id:%s" % event1.group_id),
  2349. ("issue.id", "issue.id:%s" % event1.group_id),
  2350. ]
  2351. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2352. for testdata in tests:
  2353. query = {"field": [testdata[0]], "query": testdata[1]}
  2354. response = self.do_request(query, features=features)
  2355. assert response.status_code == 200, response.content
  2356. data = response.data["data"]
  2357. assert len(data) == 1
  2358. assert data[0]["id"] == event1.event_id
  2359. assert data[0]["issue.id"] == event1.group_id
  2360. if testdata[0] == "issue":
  2361. assert data[0]["issue"] == event1.group.qualified_short_id
  2362. else:
  2363. assert data[0].get("issue", None) is None
  2364. def test_issue_negation(self):
  2365. project1 = self.create_project()
  2366. project2 = self.create_project()
  2367. event1 = self.store_event(
  2368. data={
  2369. "event_id": "a" * 32,
  2370. "transaction": "/example",
  2371. "message": "how to make fast",
  2372. "timestamp": self.ten_mins_ago,
  2373. "fingerprint": ["group_1"],
  2374. },
  2375. project_id=project1.id,
  2376. )
  2377. event2 = self.store_event(
  2378. data={
  2379. "event_id": "b" * 32,
  2380. "transaction": "/example",
  2381. "message": "go really fast plz",
  2382. "timestamp": self.ten_mins_ago,
  2383. "fingerprint": ["group_2"],
  2384. },
  2385. project_id=project2.id,
  2386. )
  2387. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2388. query = {
  2389. "field": ["title", "issue.id"],
  2390. "query": f"!issue:{event1.group.qualified_short_id}",
  2391. }
  2392. response = self.do_request(query, features=features)
  2393. assert response.status_code == 200, response.content
  2394. data = response.data["data"]
  2395. assert len(data) == 1
  2396. assert data[0]["title"] == event2.title
  2397. assert data[0]["issue.id"] == event2.group_id
  2398. def test_search_for_nonexistent_issue(self):
  2399. self.store_event(
  2400. data={
  2401. "event_id": "a" * 32,
  2402. "transaction": "/example",
  2403. "message": "how to make fast",
  2404. "timestamp": self.ten_mins_ago,
  2405. "fingerprint": ["group_1"],
  2406. },
  2407. project_id=self.project.id,
  2408. )
  2409. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2410. query = {"field": ["count()"], "query": "issue.id:112358"}
  2411. response = self.do_request(query, features=features)
  2412. assert response.status_code == 200, response.content
  2413. data = response.data["data"]
  2414. assert len(data) == 1
  2415. assert data[0]["count()"] == 0
  2416. def test_issue_alias_inside_aggregate(self):
  2417. self.store_event(
  2418. data={
  2419. "event_id": "a" * 32,
  2420. "transaction": "/example",
  2421. "message": "how to make fast",
  2422. "timestamp": self.ten_mins_ago,
  2423. "fingerprint": ["group_1"],
  2424. },
  2425. project_id=self.project.id,
  2426. )
  2427. self.store_event(
  2428. data={
  2429. "event_id": "b" * 32,
  2430. "transaction": "/example",
  2431. "message": "how to make fast",
  2432. "timestamp": self.ten_mins_ago,
  2433. "fingerprint": ["group_2"],
  2434. },
  2435. project_id=self.project.id,
  2436. )
  2437. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2438. query = {
  2439. "field": ["project", "count(id)", "count_unique(issue.id)", "count_unique(issue)"],
  2440. "sort": "-count(id)",
  2441. "statsPeriod": "24h",
  2442. }
  2443. response = self.do_request(query, features=features)
  2444. assert response.status_code == 200, response.content
  2445. data = response.data["data"]
  2446. assert len(data) == 1
  2447. assert data[0]["count(id)"] == 2
  2448. assert data[0]["count_unique(issue.id)"] == 2
  2449. assert data[0]["count_unique(issue)"] == 2
  2450. def test_project_alias_inside_aggregate(self):
  2451. project1 = self.create_project()
  2452. project2 = self.create_project()
  2453. self.store_event(
  2454. data={
  2455. "event_id": "a" * 32,
  2456. "transaction": "/example",
  2457. "message": "how to make fast",
  2458. "timestamp": self.ten_mins_ago,
  2459. "fingerprint": ["group_1"],
  2460. },
  2461. project_id=project1.id,
  2462. )
  2463. self.store_event(
  2464. data={
  2465. "event_id": "b" * 32,
  2466. "transaction": "/example",
  2467. "message": "how to make fast",
  2468. "timestamp": self.ten_mins_ago,
  2469. "fingerprint": ["group_2"],
  2470. },
  2471. project_id=project2.id,
  2472. )
  2473. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2474. query = {
  2475. "field": [
  2476. "event.type",
  2477. "count(id)",
  2478. "count_unique(project.id)",
  2479. "count_unique(project)",
  2480. ],
  2481. "sort": "-count(id)",
  2482. "statsPeriod": "24h",
  2483. }
  2484. response = self.do_request(query, features=features)
  2485. assert response.status_code == 200, response.content
  2486. data = response.data["data"]
  2487. assert len(data) == 1
  2488. assert data[0]["count(id)"] == 2
  2489. assert data[0]["count_unique(project.id)"] == 2
  2490. assert data[0]["count_unique(project)"] == 2
  2491. def test_user_display(self):
  2492. project1 = self.create_project()
  2493. project2 = self.create_project()
  2494. self.store_event(
  2495. data={
  2496. "event_id": "a" * 32,
  2497. "transaction": "/example",
  2498. "message": "how to make fast",
  2499. "timestamp": self.ten_mins_ago,
  2500. "user": {"email": "cathy@example.com"},
  2501. },
  2502. project_id=project1.id,
  2503. )
  2504. self.store_event(
  2505. data={
  2506. "event_id": "b" * 32,
  2507. "transaction": "/example",
  2508. "message": "how to make fast",
  2509. "timestamp": self.ten_mins_ago,
  2510. "user": {"username": "catherine"},
  2511. },
  2512. project_id=project2.id,
  2513. )
  2514. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2515. query = {
  2516. "field": ["event.type", "user.display"],
  2517. "query": "user.display:cath*",
  2518. "statsPeriod": "24h",
  2519. }
  2520. response = self.do_request(query, features=features)
  2521. assert response.status_code == 200, response.content
  2522. data = response.data["data"]
  2523. assert len(data) == 2
  2524. result = {r["user.display"] for r in data}
  2525. assert result == {"catherine", "cathy@example.com"}
  2526. def test_user_display_with_aggregates(self):
  2527. self.store_event(
  2528. data={
  2529. "event_id": "a" * 32,
  2530. "transaction": "/example",
  2531. "message": "how to make fast",
  2532. "timestamp": self.ten_mins_ago,
  2533. "user": {"email": "cathy@example.com"},
  2534. },
  2535. project_id=self.project.id,
  2536. )
  2537. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2538. query = {
  2539. "field": ["event.type", "user.display", "count_unique(title)"],
  2540. "statsPeriod": "24h",
  2541. }
  2542. response = self.do_request(query, features=features)
  2543. assert response.status_code == 200, response.content
  2544. data = response.data["data"]
  2545. assert len(data) == 1
  2546. result = {r["user.display"] for r in data}
  2547. assert result == {"cathy@example.com"}
  2548. query = {"field": ["event.type", "count_unique(user.display)"], "statsPeriod": "24h"}
  2549. response = self.do_request(query, features=features)
  2550. assert response.status_code == 200, response.content
  2551. data = response.data["data"]
  2552. assert len(data) == 1
  2553. assert data[0]["count_unique(user.display)"] == 1
  2554. def test_orderby_user_display(self):
  2555. project1 = self.create_project()
  2556. project2 = self.create_project()
  2557. self.store_event(
  2558. data={
  2559. "event_id": "a" * 32,
  2560. "transaction": "/example",
  2561. "message": "how to make fast",
  2562. "timestamp": self.ten_mins_ago,
  2563. "user": {"email": "cathy@example.com"},
  2564. },
  2565. project_id=project1.id,
  2566. )
  2567. self.store_event(
  2568. data={
  2569. "event_id": "b" * 32,
  2570. "transaction": "/example",
  2571. "message": "how to make fast",
  2572. "timestamp": self.ten_mins_ago,
  2573. "user": {"username": "catherine"},
  2574. },
  2575. project_id=project2.id,
  2576. )
  2577. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2578. query = {
  2579. "field": ["event.type", "user.display"],
  2580. "query": "user.display:cath*",
  2581. "statsPeriod": "24h",
  2582. "orderby": "-user.display",
  2583. }
  2584. response = self.do_request(query, features=features)
  2585. assert response.status_code == 200, response.content
  2586. data = response.data["data"]
  2587. assert len(data) == 2
  2588. result = [r["user.display"] for r in data]
  2589. # because we're ordering by `-user.display`, we expect the results in reverse sorted order
  2590. assert result == ["cathy@example.com", "catherine"]
  2591. def test_orderby_user_display_with_aggregates(self):
  2592. project1 = self.create_project()
  2593. project2 = self.create_project()
  2594. self.store_event(
  2595. data={
  2596. "event_id": "a" * 32,
  2597. "transaction": "/example",
  2598. "message": "how to make fast",
  2599. "timestamp": self.ten_mins_ago,
  2600. "user": {"email": "cathy@example.com"},
  2601. },
  2602. project_id=project1.id,
  2603. )
  2604. self.store_event(
  2605. data={
  2606. "event_id": "b" * 32,
  2607. "transaction": "/example",
  2608. "message": "how to make fast",
  2609. "timestamp": self.ten_mins_ago,
  2610. "user": {"username": "catherine"},
  2611. },
  2612. project_id=project2.id,
  2613. )
  2614. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2615. query = {
  2616. "field": ["event.type", "user.display", "count_unique(title)"],
  2617. "query": "user.display:cath*",
  2618. "statsPeriod": "24h",
  2619. "orderby": "user.display",
  2620. }
  2621. response = self.do_request(query, features=features)
  2622. assert response.status_code == 200, response.content
  2623. data = response.data["data"]
  2624. assert len(data) == 2
  2625. result = [r["user.display"] for r in data]
  2626. # because we're ordering by `user.display`, we expect the results in sorted order
  2627. assert result == ["catherine", "cathy@example.com"]
  2628. def test_any_field_alias(self):
  2629. day_ago = before_now(days=1).replace(hour=10, minute=11, second=12, microsecond=13)
  2630. self.store_event(
  2631. data={
  2632. "event_id": "a" * 32,
  2633. "transaction": "/example",
  2634. "message": "how to make fast",
  2635. "timestamp": iso_format(day_ago),
  2636. "user": {"email": "cathy@example.com"},
  2637. },
  2638. project_id=self.project.id,
  2639. )
  2640. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2641. query = {
  2642. "field": [
  2643. "event.type",
  2644. "any(user.display)",
  2645. "any(timestamp.to_day)",
  2646. "any(timestamp.to_hour)",
  2647. ],
  2648. "statsPeriod": "7d",
  2649. }
  2650. response = self.do_request(query, features=features)
  2651. assert response.status_code == 200, response.content
  2652. data = response.data["data"]
  2653. assert len(data) == 1
  2654. result = {r["any(user.display)"] for r in data}
  2655. assert result == {"cathy@example.com"}
  2656. result = {r["any(timestamp.to_day)"][:19] for r in data}
  2657. assert result == {iso_format(day_ago.replace(hour=0, minute=0, second=0, microsecond=0))}
  2658. result = {r["any(timestamp.to_hour)"][:19] for r in data}
  2659. assert result == {iso_format(day_ago.replace(minute=0, second=0, microsecond=0))}
  2660. def test_field_aliases_in_conflicting_functions(self):
  2661. self.store_event(
  2662. data={
  2663. "event_id": "a" * 32,
  2664. "transaction": "/example",
  2665. "message": "how to make fast",
  2666. "timestamp": iso_format(
  2667. before_now(days=1).replace(hour=10, minute=11, second=12, microsecond=13)
  2668. ),
  2669. "user": {"email": "cathy@example.com"},
  2670. },
  2671. project_id=self.project.id,
  2672. )
  2673. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2674. field_aliases = ["user.display", "timestamp.to_day", "timestamp.to_hour"]
  2675. for alias in field_aliases:
  2676. query = {
  2677. "field": [alias, f"any({alias})"],
  2678. "statsPeriod": "7d",
  2679. }
  2680. response = self.do_request(query, features=features)
  2681. assert response.status_code == 400, response.content
  2682. assert (
  2683. response.data["detail"]
  2684. == f"A single field cannot be used both inside and outside a function in the same query. To use {alias} you must first remove the function(s): any({alias})"
  2685. )
  2686. @pytest.mark.skip(
  2687. """
  2688. For some reason ClickHouse errors when there are two of the same string literals
  2689. (in this case the empty string "") in a query and one is in the prewhere clause.
  2690. Does not affect production or ClickHouse versions > 20.4.
  2691. """
  2692. )
  2693. def test_has_message(self):
  2694. event = self.store_event(
  2695. {"timestamp": self.ten_mins_ago, "message": "a"}, project_id=self.project.id
  2696. )
  2697. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2698. query = {"field": ["project", "message"], "query": "has:message", "statsPeriod": "14d"}
  2699. response = self.do_request(query, features=features)
  2700. assert response.status_code == 200, response.content
  2701. assert len(response.data["data"]) == 1
  2702. assert response.data["data"][0]["message"] == event.message
  2703. query = {"field": ["project", "message"], "query": "!has:message", "statsPeriod": "14d"}
  2704. response = self.do_request(query, features=features)
  2705. assert response.status_code == 200, response.content
  2706. assert len(response.data["data"]) == 0
  2707. def test_has_transaction_status(self):
  2708. self.store_event(self.transaction_data, project_id=self.project.id)
  2709. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2710. query = {
  2711. "field": ["event.type", "count(id)"],
  2712. "query": "event.type:transaction has:transaction.status",
  2713. "sort": "-count(id)",
  2714. "statsPeriod": "24h",
  2715. }
  2716. response = self.do_request(query, features=features)
  2717. assert response.status_code == 200, response.content
  2718. data = response.data["data"]
  2719. assert len(data) == 1
  2720. assert data[0]["count(id)"] == 1
  2721. def test_not_has_transaction_status(self):
  2722. self.store_event(self.transaction_data, project_id=self.project.id)
  2723. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2724. query = {
  2725. "field": ["event.type", "count(id)"],
  2726. "query": "event.type:transaction !has:transaction.status",
  2727. "sort": "-count(id)",
  2728. "statsPeriod": "24h",
  2729. }
  2730. response = self.do_request(query, features=features)
  2731. assert response.status_code == 200, response.content
  2732. data = response.data["data"]
  2733. assert len(data) == 1
  2734. assert data[0]["count(id)"] == 0
  2735. def test_tag_that_looks_like_aggregation(self):
  2736. data = {
  2737. "message": "Failure state",
  2738. "timestamp": self.ten_mins_ago,
  2739. "tags": {"count_diff": 99},
  2740. }
  2741. self.store_event(data, project_id=self.project.id)
  2742. query = {
  2743. "field": ["message", "count_diff", "count()"],
  2744. "query": "",
  2745. "project": [self.project.id],
  2746. "statsPeriod": "24h",
  2747. }
  2748. response = self.do_request(query)
  2749. assert response.status_code == 200, response.content
  2750. meta = response.data["meta"]["fields"]
  2751. assert "string" == meta["count_diff"], "tags should not be counted as integers"
  2752. assert "string" == meta["message"]
  2753. assert "integer" == meta["count()"]
  2754. assert 1 == len(response.data["data"])
  2755. data = response.data["data"][0]
  2756. assert "99" == data["count_diff"]
  2757. assert "Failure state" == data["message"]
  2758. assert 1 == data["count()"]
  2759. def test_aggregate_negation(self):
  2760. data = self.load_data(
  2761. timestamp=before_now(minutes=10),
  2762. duration=timedelta(seconds=5),
  2763. )
  2764. self.store_event(data, project_id=self.project.id)
  2765. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2766. query = {
  2767. "field": ["event.type", "count()"],
  2768. "query": "event.type:transaction count():1",
  2769. "statsPeriod": "24h",
  2770. }
  2771. response = self.do_request(query, features=features)
  2772. assert response.status_code == 200, response.content
  2773. data = response.data["data"]
  2774. assert len(data) == 1
  2775. query = {
  2776. "field": ["event.type", "count()"],
  2777. "query": "event.type:transaction !count():1",
  2778. "statsPeriod": "24h",
  2779. }
  2780. response = self.do_request(query, features=features)
  2781. assert response.status_code == 200, response.content
  2782. data = response.data["data"]
  2783. assert len(data) == 0
  2784. def test_all_aggregates_in_columns(self):
  2785. data = self.load_data(
  2786. timestamp=before_now(minutes=11),
  2787. duration=timedelta(seconds=5),
  2788. )
  2789. data["transaction"] = "/failure_rate/1"
  2790. self.store_event(data, project_id=self.project.id)
  2791. data = self.load_data(
  2792. timestamp=before_now(minutes=10),
  2793. duration=timedelta(seconds=5),
  2794. )
  2795. data["transaction"] = "/failure_rate/1"
  2796. data["contexts"]["trace"]["status"] = "unauthenticated"
  2797. event = self.store_event(data, project_id=self.project.id)
  2798. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2799. query = {
  2800. "field": [
  2801. "event.type",
  2802. "p50()",
  2803. "p75()",
  2804. "p95()",
  2805. "p99()",
  2806. "p100()",
  2807. "percentile(transaction.duration, 0.99)",
  2808. "apdex(300)",
  2809. "count_miserable(user, 300)",
  2810. "user_misery(300)",
  2811. "failure_rate()",
  2812. ],
  2813. "query": "event.type:transaction",
  2814. }
  2815. response = self.do_request(query, features=features)
  2816. assert response.status_code == 200, response.content
  2817. meta = response.data["meta"]["fields"]
  2818. units = response.data["meta"]["units"]
  2819. assert meta["p50()"] == "duration"
  2820. assert meta["p75()"] == "duration"
  2821. assert meta["p95()"] == "duration"
  2822. assert meta["p99()"] == "duration"
  2823. assert meta["p100()"] == "duration"
  2824. assert meta["percentile(transaction.duration, 0.99)"] == "duration"
  2825. assert meta["apdex(300)"] == "number"
  2826. assert meta["failure_rate()"] == "percentage"
  2827. assert meta["user_misery(300)"] == "number"
  2828. assert meta["count_miserable(user, 300)"] == "integer"
  2829. assert units["p50()"] == "millisecond"
  2830. assert units["p75()"] == "millisecond"
  2831. assert units["p95()"] == "millisecond"
  2832. assert units["p99()"] == "millisecond"
  2833. assert units["p100()"] == "millisecond"
  2834. assert units["percentile(transaction.duration, 0.99)"] == "millisecond"
  2835. data = response.data["data"]
  2836. assert len(data) == 1
  2837. assert data[0]["p50()"] == 5000
  2838. assert data[0]["p75()"] == 5000
  2839. assert data[0]["p95()"] == 5000
  2840. assert data[0]["p99()"] == 5000
  2841. assert data[0]["p100()"] == 5000
  2842. assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
  2843. assert data[0]["apdex(300)"] == 0.0
  2844. assert data[0]["count_miserable(user, 300)"] == 1
  2845. assert data[0]["user_misery(300)"] == 0.058
  2846. assert data[0]["failure_rate()"] == 0.5
  2847. features = {
  2848. "organizations:discover-basic": True,
  2849. "organizations:global-views": True,
  2850. }
  2851. query = {
  2852. "field": [
  2853. "event.type",
  2854. "p50()",
  2855. "p75()",
  2856. "p95()",
  2857. "p99()",
  2858. "p100()",
  2859. "percentile(transaction.duration, 0.99)",
  2860. "apdex(300)",
  2861. "apdex()",
  2862. "count_miserable(user, 300)",
  2863. "user_misery(300)",
  2864. "failure_rate()",
  2865. "count_miserable(user)",
  2866. "user_misery()",
  2867. ],
  2868. "query": "event.type:transaction",
  2869. "project": [self.project.id],
  2870. }
  2871. response = self.do_request(query, features=features)
  2872. assert response.status_code == 200, response.content
  2873. meta = response.data["meta"]["fields"]
  2874. units = response.data["meta"]["units"]
  2875. assert meta["p50()"] == "duration"
  2876. assert meta["p75()"] == "duration"
  2877. assert meta["p95()"] == "duration"
  2878. assert meta["p99()"] == "duration"
  2879. assert meta["p100()"] == "duration"
  2880. assert meta["percentile(transaction.duration, 0.99)"] == "duration"
  2881. assert meta["apdex(300)"] == "number"
  2882. assert meta["apdex()"] == "number"
  2883. assert meta["failure_rate()"] == "percentage"
  2884. assert meta["user_misery(300)"] == "number"
  2885. assert meta["count_miserable(user, 300)"] == "integer"
  2886. assert meta["project_threshold_config"] == "string"
  2887. assert meta["user_misery()"] == "number"
  2888. assert meta["count_miserable(user)"] == "integer"
  2889. assert units["p50()"] == "millisecond"
  2890. assert units["p75()"] == "millisecond"
  2891. assert units["p95()"] == "millisecond"
  2892. assert units["p99()"] == "millisecond"
  2893. assert units["p100()"] == "millisecond"
  2894. assert units["percentile(transaction.duration, 0.99)"] == "millisecond"
  2895. data = response.data["data"]
  2896. assert len(data) == 1
  2897. assert data[0]["p50()"] == 5000
  2898. assert data[0]["p75()"] == 5000
  2899. assert data[0]["p95()"] == 5000
  2900. assert data[0]["p99()"] == 5000
  2901. assert data[0]["p100()"] == 5000
  2902. assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
  2903. assert data[0]["apdex(300)"] == 0.0
  2904. assert data[0]["apdex()"] == 0.0
  2905. assert data[0]["count_miserable(user, 300)"] == 1
  2906. assert data[0]["user_misery(300)"] == 0.058
  2907. assert data[0]["failure_rate()"] == 0.5
  2908. assert data[0]["project_threshold_config"] == ["duration", 300]
  2909. assert data[0]["user_misery()"] == 0.058
  2910. assert data[0]["count_miserable(user)"] == 1
  2911. query = {
  2912. "field": ["event.type", "last_seen()", "latest_event()"],
  2913. "query": "event.type:transaction",
  2914. }
  2915. response = self.do_request(query, features=features)
  2916. assert response.status_code == 200, response.content
  2917. data = response.data["data"]
  2918. assert len(data) == 1
  2919. assert self.ten_mins_ago[:-5] in data[0]["last_seen()"]
  2920. assert data[0]["latest_event()"] == event.event_id
  2921. query = {
  2922. "field": [
  2923. "event.type",
  2924. "count()",
  2925. "count(id)",
  2926. "count_unique(project)",
  2927. "min(transaction.duration)",
  2928. "max(transaction.duration)",
  2929. "avg(transaction.duration)",
  2930. "stddev(transaction.duration)",
  2931. "var(transaction.duration)",
  2932. "cov(transaction.duration, transaction.duration)",
  2933. "corr(transaction.duration, transaction.duration)",
  2934. "sum(transaction.duration)",
  2935. ],
  2936. "query": "event.type:transaction",
  2937. }
  2938. response = self.do_request(query, features=features)
  2939. assert response.status_code == 200, response.content
  2940. data = response.data["data"]
  2941. assert len(data) == 1
  2942. assert data[0]["count()"] == 2
  2943. assert data[0]["count(id)"] == 2
  2944. assert data[0]["count_unique(project)"] == 1
  2945. assert data[0]["min(transaction.duration)"] == 5000
  2946. assert data[0]["max(transaction.duration)"] == 5000
  2947. assert data[0]["avg(transaction.duration)"] == 5000
  2948. assert data[0]["stddev(transaction.duration)"] == 0.0
  2949. assert data[0]["var(transaction.duration)"] == 0.0
  2950. assert data[0]["cov(transaction.duration, transaction.duration)"] == 0.0
  2951. assert data[0]["corr(transaction.duration, transaction.duration)"] == 0.0
  2952. assert data[0]["sum(transaction.duration)"] == 10000
  2953. @requires_not_arm64
  2954. def test_null_user_misery_returns_zero(self):
  2955. self.transaction_data["user"] = None
  2956. self.transaction_data["transaction"] = "/no_users/1"
  2957. self.store_event(self.transaction_data, project_id=self.project.id)
  2958. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  2959. query = {
  2960. "field": ["user_misery(300)"],
  2961. "query": "event.type:transaction",
  2962. }
  2963. response = self.do_request(query, features=features)
  2964. assert response.status_code == 200, response.content
  2965. meta = response.data["meta"]["fields"]
  2966. assert meta["user_misery(300)"] == "number"
  2967. data = response.data["data"]
  2968. assert data[0]["user_misery(300)"] == 0
  2969. @requires_not_arm64
  2970. def test_null_user_misery_new_returns_zero(self):
  2971. self.transaction_data["user"] = None
  2972. self.transaction_data["transaction"] = "/no_users/1"
  2973. self.store_event(self.transaction_data, project_id=self.project.id)
  2974. features = {
  2975. "organizations:discover-basic": True,
  2976. }
  2977. query = {
  2978. "field": ["user_misery()"],
  2979. "query": "event.type:transaction",
  2980. }
  2981. response = self.do_request(query, features=features)
  2982. assert response.status_code == 200, response.content
  2983. meta = response.data["meta"]["fields"]
  2984. assert meta["user_misery()"] == "number"
  2985. data = response.data["data"]
  2986. assert data[0]["user_misery()"] == 0
  2987. def test_all_aggregates_in_query(self):
  2988. data = self.load_data(
  2989. timestamp=before_now(minutes=11),
  2990. duration=timedelta(seconds=5),
  2991. )
  2992. data["transaction"] = "/failure_rate/1"
  2993. self.store_event(data, project_id=self.project.id)
  2994. data = self.load_data(
  2995. timestamp=before_now(minutes=10),
  2996. duration=timedelta(seconds=5),
  2997. )
  2998. data["transaction"] = "/failure_rate/2"
  2999. data["contexts"]["trace"]["status"] = "unauthenticated"
  3000. self.store_event(data, project_id=self.project.id)
  3001. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3002. query = {
  3003. "field": [
  3004. "event.type",
  3005. "p50()",
  3006. "p75()",
  3007. "p95()",
  3008. "percentile(transaction.duration, 0.99)",
  3009. "p100()",
  3010. ],
  3011. "query": "event.type:transaction p50():>100 p75():>1000 p95():>1000 p100():>1000 percentile(transaction.duration, 0.99):>1000",
  3012. }
  3013. response = self.do_request(query, features=features)
  3014. assert response.status_code == 200, response.content
  3015. data = response.data["data"]
  3016. assert len(data) == 1
  3017. assert data[0]["p50()"] == 5000
  3018. assert data[0]["p75()"] == 5000
  3019. assert data[0]["p95()"] == 5000
  3020. assert data[0]["p100()"] == 5000
  3021. assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
  3022. query = {
  3023. "field": [
  3024. "event.type",
  3025. "apdex(300)",
  3026. "count_miserable(user, 300)",
  3027. "user_misery(300)",
  3028. "failure_rate()",
  3029. ],
  3030. "query": "event.type:transaction apdex(300):>-1.0 failure_rate():>0.25",
  3031. }
  3032. response = self.do_request(query, features=features)
  3033. assert response.status_code == 200, response.content
  3034. data = response.data["data"]
  3035. assert len(data) == 1
  3036. assert data[0]["apdex(300)"] == 0.0
  3037. assert data[0]["count_miserable(user, 300)"] == 1
  3038. assert data[0]["user_misery(300)"] == 0.058
  3039. assert data[0]["failure_rate()"] == 0.5
  3040. query = {
  3041. "field": ["event.type", "last_seen()", "latest_event()"],
  3042. "query": "event.type:transaction last_seen():>1990-12-01T00:00:00",
  3043. }
  3044. response = self.do_request(query, features=features)
  3045. assert response.status_code == 200, response.content
  3046. data = response.data["data"]
  3047. assert len(data) == 1
  3048. query = {
  3049. "field": ["event.type", "count()", "count(id)", "count_unique(transaction)"],
  3050. "query": "event.type:transaction count():>1 count(id):>1 count_unique(transaction):>1",
  3051. }
  3052. response = self.do_request(query, features=features)
  3053. assert response.status_code == 200, response.content
  3054. data = response.data["data"]
  3055. assert len(data) == 1
  3056. assert data[0]["count()"] == 2
  3057. assert data[0]["count(id)"] == 2
  3058. assert data[0]["count_unique(transaction)"] == 2
  3059. query = {
  3060. "field": [
  3061. "event.type",
  3062. "min(transaction.duration)",
  3063. "max(transaction.duration)",
  3064. "avg(transaction.duration)",
  3065. "sum(transaction.duration)",
  3066. "stddev(transaction.duration)",
  3067. "var(transaction.duration)",
  3068. "cov(transaction.duration, transaction.duration)",
  3069. "corr(transaction.duration, transaction.duration)",
  3070. ],
  3071. "query": " ".join(
  3072. [
  3073. "event.type:transaction",
  3074. "min(transaction.duration):>1000",
  3075. "max(transaction.duration):>1000",
  3076. "avg(transaction.duration):>1000",
  3077. "sum(transaction.duration):>1000",
  3078. "stddev(transaction.duration):>=0.0",
  3079. "var(transaction.duration):>=0.0",
  3080. "cov(transaction.duration, transaction.duration):>=0.0",
  3081. # correlation is nan because variance is 0
  3082. # "corr(transaction.duration, transaction.duration):>=0.0",
  3083. ]
  3084. ),
  3085. }
  3086. response = self.do_request(query, features=features)
  3087. assert response.status_code == 200, response.content
  3088. data = response.data["data"]
  3089. assert len(data) == 1
  3090. assert data[0]["min(transaction.duration)"] == 5000
  3091. assert data[0]["max(transaction.duration)"] == 5000
  3092. assert data[0]["avg(transaction.duration)"] == 5000
  3093. assert data[0]["sum(transaction.duration)"] == 10000
  3094. assert data[0]["stddev(transaction.duration)"] == 0.0
  3095. assert data[0]["var(transaction.duration)"] == 0.0
  3096. assert data[0]["cov(transaction.duration, transaction.duration)"] == 0.0
  3097. assert data[0]["corr(transaction.duration, transaction.duration)"] == 0.0
  3098. query = {
  3099. "field": ["event.type", "apdex(400)"],
  3100. "query": "event.type:transaction apdex(400):0",
  3101. }
  3102. response = self.do_request(query, features=features)
  3103. assert response.status_code == 200, response.content
  3104. data = response.data["data"]
  3105. assert len(data) == 1
  3106. assert data[0]["apdex(400)"] == 0
  3107. def test_functions_in_orderby(self):
  3108. data = self.load_data(
  3109. timestamp=before_now(minutes=11),
  3110. duration=timedelta(seconds=5),
  3111. )
  3112. data["transaction"] = "/failure_rate/1"
  3113. self.store_event(data, project_id=self.project.id)
  3114. data = self.load_data(
  3115. timestamp=before_now(minutes=10),
  3116. duration=timedelta(seconds=5),
  3117. )
  3118. data["transaction"] = "/failure_rate/2"
  3119. data["contexts"]["trace"]["status"] = "unauthenticated"
  3120. event = self.store_event(data, project_id=self.project.id)
  3121. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3122. query = {
  3123. "field": ["event.type", "p75()"],
  3124. "sort": "-p75",
  3125. "query": "event.type:transaction",
  3126. }
  3127. response = self.do_request(query, features=features)
  3128. assert response.status_code == 200, response.content
  3129. data = response.data["data"]
  3130. assert len(data) == 1
  3131. assert data[0]["p75()"] == 5000
  3132. query = {
  3133. "field": ["event.type", "percentile(transaction.duration, 0.99)"],
  3134. "sort": "-percentile_transaction_duration_0_99",
  3135. "query": "event.type:transaction",
  3136. }
  3137. response = self.do_request(query, features=features)
  3138. assert response.status_code == 200, response.content
  3139. data = response.data["data"]
  3140. assert len(data) == 1
  3141. assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
  3142. query = {
  3143. "field": ["event.type", "apdex(300)"],
  3144. "sort": "-apdex(300)",
  3145. "query": "event.type:transaction",
  3146. }
  3147. response = self.do_request(query, features=features)
  3148. assert response.status_code == 200, response.content
  3149. data = response.data["data"]
  3150. assert len(data) == 1
  3151. assert data[0]["apdex(300)"] == 0.0
  3152. query = {
  3153. "field": ["event.type", "latest_event()"],
  3154. "query": "event.type:transaction",
  3155. "sort": "latest_event",
  3156. }
  3157. response = self.do_request(query, features=features)
  3158. assert response.status_code == 200, response.content
  3159. data = response.data["data"]
  3160. assert len(data) == 1
  3161. assert data[0]["latest_event()"] == event.event_id
  3162. query = {
  3163. "field": ["event.type", "count_unique(transaction)"],
  3164. "query": "event.type:transaction",
  3165. "sort": "-count_unique_transaction",
  3166. }
  3167. response = self.do_request(query, features=features)
  3168. assert response.status_code == 200, response.content
  3169. data = response.data["data"]
  3170. assert len(data) == 1
  3171. assert data[0]["count_unique(transaction)"] == 2
  3172. query = {
  3173. "field": ["event.type", "min(transaction.duration)"],
  3174. "query": "event.type:transaction",
  3175. "sort": "-min_transaction_duration",
  3176. }
  3177. response = self.do_request(query, features=features)
  3178. assert response.status_code == 200, response.content
  3179. data = response.data["data"]
  3180. assert len(data) == 1
  3181. assert data[0]["min(transaction.duration)"] == 5000
  3182. def test_issue_alias_in_aggregate(self):
  3183. self.store_event(
  3184. data={
  3185. "event_id": "a" * 32,
  3186. "timestamp": self.eleven_mins_ago,
  3187. "fingerprint": ["group_1"],
  3188. },
  3189. project_id=self.project.id,
  3190. )
  3191. self.store_event(
  3192. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_2"]},
  3193. project_id=self.project.id,
  3194. )
  3195. query = {"field": ["event.type", "count_unique(issue)"], "query": "count_unique(issue):>1"}
  3196. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3197. response = self.do_request(query, features=features)
  3198. assert response.status_code == 200, response.content
  3199. data = response.data["data"]
  3200. assert len(data) == 1
  3201. assert data[0]["count_unique(issue)"] == 2
  3202. def test_deleted_issue_in_results(self):
  3203. event1 = self.store_event(
  3204. data={
  3205. "event_id": "a" * 32,
  3206. "timestamp": self.eleven_mins_ago,
  3207. "fingerprint": ["group_1"],
  3208. },
  3209. project_id=self.project.id,
  3210. )
  3211. event2 = self.store_event(
  3212. data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_2"]},
  3213. project_id=self.project.id,
  3214. )
  3215. event2.group.delete()
  3216. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3217. query = {"field": ["issue", "count()"], "sort": "issue.id"}
  3218. response = self.do_request(query, features=features)
  3219. assert response.status_code == 200, response.content
  3220. data = response.data["data"]
  3221. assert len(data) == 2
  3222. assert data[0]["issue"] == event1.group.qualified_short_id
  3223. assert data[1]["issue"] == "unknown"
  3224. def test_last_seen_negative_duration(self):
  3225. self.store_event(
  3226. data={"event_id": "f" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_1"]},
  3227. project_id=self.project.id,
  3228. )
  3229. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3230. query = {"field": ["id", "last_seen()"], "query": "last_seen():-30d"}
  3231. response = self.do_request(query, features=features)
  3232. assert response.status_code == 200, response.content
  3233. data = response.data["data"]
  3234. assert len(data) == 1
  3235. assert data[0]["id"] == "f" * 32
  3236. def test_last_seen_aggregate_condition(self):
  3237. self.store_event(
  3238. data={"event_id": "f" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group_1"]},
  3239. project_id=self.project.id,
  3240. )
  3241. query = {
  3242. "field": ["id", "last_seen()"],
  3243. "query": f"last_seen():>{iso_format(before_now(days=30))}",
  3244. }
  3245. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3246. response = self.do_request(query, features=features)
  3247. assert response.status_code == 200, response.content
  3248. data = response.data["data"]
  3249. assert len(data) == 1
  3250. assert data[0]["id"] == "f" * 32
  3251. def test_conditional_filter(self):
  3252. for v in ["a", "b"]:
  3253. self.store_event(
  3254. data={
  3255. "event_id": v * 32,
  3256. "timestamp": self.ten_mins_ago,
  3257. "fingerprint": ["group_1"],
  3258. },
  3259. project_id=self.project.id,
  3260. )
  3261. query = {
  3262. "field": ["id"],
  3263. "query": "id:{} OR id:{}".format("a" * 32, "b" * 32),
  3264. "orderby": "id",
  3265. }
  3266. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3267. response = self.do_request(query, features=features)
  3268. assert response.status_code == 200, response.content
  3269. data = response.data["data"]
  3270. assert len(data) == 2
  3271. assert data[0]["id"] == "a" * 32
  3272. assert data[1]["id"] == "b" * 32
  3273. def test_aggregation_comparison_with_conditional_filter(self):
  3274. self.store_event(
  3275. data={
  3276. "event_id": "a" * 32,
  3277. "timestamp": self.ten_mins_ago,
  3278. "fingerprint": ["group_1"],
  3279. "user": {"email": "foo@example.com"},
  3280. "environment": "prod",
  3281. },
  3282. project_id=self.project.id,
  3283. )
  3284. self.store_event(
  3285. data={
  3286. "event_id": "b" * 32,
  3287. "timestamp": self.ten_mins_ago,
  3288. "fingerprint": ["group_2"],
  3289. "user": {"email": "foo@example.com"},
  3290. "environment": "staging",
  3291. },
  3292. project_id=self.project.id,
  3293. )
  3294. event = self.store_event(
  3295. data={
  3296. "event_id": "c" * 32,
  3297. "timestamp": self.ten_mins_ago,
  3298. "fingerprint": ["group_2"],
  3299. "user": {"email": "foo@example.com"},
  3300. "environment": "prod",
  3301. },
  3302. project_id=self.project.id,
  3303. )
  3304. self.store_event(
  3305. data={
  3306. "event_id": "d" * 32,
  3307. "timestamp": self.ten_mins_ago,
  3308. "fingerprint": ["group_2"],
  3309. "user": {"email": "foo@example.com"},
  3310. "environment": "canary",
  3311. },
  3312. project_id=self.project.id,
  3313. )
  3314. query = {
  3315. "field": ["issue.id", "count(id)"],
  3316. "query": "count(id):>1 user.email:foo@example.com AND (environment:prod OR environment:staging)",
  3317. "orderby": "issue.id",
  3318. }
  3319. response = self.do_request(query)
  3320. assert response.status_code == 200, response.content
  3321. assert len(response.data["data"]) == 1
  3322. data = response.data["data"]
  3323. assert data[0]["issue.id"] == event.group_id
  3324. assert data[0]["count(id)"] == 2
  3325. def run_test_in_query(self, query, expected_events, expected_negative_events=None):
  3326. params = {
  3327. "field": ["id"],
  3328. "query": query,
  3329. "orderby": "id",
  3330. }
  3331. response = self.do_request(
  3332. params, {"organizations:discover-basic": True, "organizations:global-views": True}
  3333. )
  3334. assert response.status_code == 200, response.content
  3335. assert [row["id"] for row in response.data["data"]] == [e.event_id for e in expected_events]
  3336. if expected_negative_events is not None:
  3337. params["query"] = f"!{query}"
  3338. response = self.do_request(
  3339. params,
  3340. {"organizations:discover-basic": True, "organizations:global-views": True},
  3341. )
  3342. assert response.status_code == 200, response.content
  3343. assert [row["id"] for row in response.data["data"]] == [
  3344. e.event_id for e in expected_negative_events
  3345. ]
  3346. def test_in_query_events(self):
  3347. project_1 = self.create_project()
  3348. event_1 = self.store_event(
  3349. data={
  3350. "event_id": "a" * 32,
  3351. "timestamp": self.ten_mins_ago,
  3352. "fingerprint": ["group_1"],
  3353. "message": "group1",
  3354. "user": {"email": "hello@example.com"},
  3355. "environment": "prod",
  3356. "tags": {"random": "123"},
  3357. "release": "1.0",
  3358. },
  3359. project_id=project_1.id,
  3360. )
  3361. project_2 = self.create_project()
  3362. event_2 = self.store_event(
  3363. data={
  3364. "event_id": "b" * 32,
  3365. "timestamp": self.ten_mins_ago,
  3366. "fingerprint": ["group_2"],
  3367. "message": "group2",
  3368. "user": {"email": "bar@example.com"},
  3369. "environment": "staging",
  3370. "tags": {"random": "456"},
  3371. "stacktrace": {"frames": [{"filename": "src/app/group2.py"}]},
  3372. "release": "1.2",
  3373. },
  3374. project_id=project_2.id,
  3375. )
  3376. project_3 = self.create_project()
  3377. event_3 = self.store_event(
  3378. data={
  3379. "event_id": "c" * 32,
  3380. "timestamp": self.ten_mins_ago,
  3381. "fingerprint": ["group_3"],
  3382. "message": "group3",
  3383. "user": {"email": "foo@example.com"},
  3384. "environment": "canary",
  3385. "tags": {"random": "789"},
  3386. },
  3387. project_id=project_3.id,
  3388. )
  3389. self.run_test_in_query("environment:[prod, staging]", [event_1, event_2], [event_3])
  3390. self.run_test_in_query("environment:[staging]", [event_2], [event_1, event_3])
  3391. self.run_test_in_query(
  3392. "user.email:[foo@example.com, hello@example.com]", [event_1, event_3], [event_2]
  3393. )
  3394. self.run_test_in_query("user.email:[foo@example.com]", [event_3], [event_1, event_2])
  3395. self.run_test_in_query(
  3396. "user.display:[foo@example.com, hello@example.com]", [event_1, event_3], [event_2]
  3397. )
  3398. self.run_test_in_query(
  3399. 'message:["group2 src/app/group2.py in ?", group1]', [event_1, event_2], [event_3]
  3400. )
  3401. self.run_test_in_query(
  3402. f"issue.id:[{event_1.group_id},{event_2.group_id}]", [event_1, event_2]
  3403. )
  3404. self.run_test_in_query(
  3405. f"issue:[{event_1.group.qualified_short_id},{event_2.group.qualified_short_id}]",
  3406. [event_1, event_2],
  3407. )
  3408. self.run_test_in_query(
  3409. f"issue:[{event_1.group.qualified_short_id},{event_2.group.qualified_short_id}, unknown]",
  3410. [event_1, event_2],
  3411. )
  3412. self.run_test_in_query(f"project_id:[{project_3.id},{project_2.id}]", [event_2, event_3])
  3413. self.run_test_in_query(
  3414. f"project.name:[{project_3.slug},{project_2.slug}]", [event_2, event_3]
  3415. )
  3416. self.run_test_in_query("random:[789,456]", [event_2, event_3], [event_1])
  3417. self.run_test_in_query("tags[random]:[789,456]", [event_2, event_3], [event_1])
  3418. self.run_test_in_query("release:[1.0,1.2]", [event_1, event_2], [event_3])
  3419. def test_in_query_events_stack(self):
  3420. test_js = self.store_event(
  3421. self.load_data(
  3422. platform="javascript",
  3423. timestamp=before_now(minutes=10),
  3424. duration=timedelta(seconds=5),
  3425. ),
  3426. project_id=self.project.id,
  3427. )
  3428. test_java = self.store_event(
  3429. self.load_data(
  3430. platform="java",
  3431. timestamp=before_now(minutes=10),
  3432. duration=timedelta(seconds=5),
  3433. ),
  3434. project_id=self.project.id,
  3435. )
  3436. self.run_test_in_query(
  3437. "stack.filename:[../../sentry/scripts/views.js]", [test_js], [test_java]
  3438. )
  3439. def test_in_query_transactions(self):
  3440. data = self.transaction_data.copy()
  3441. data["event_id"] = "a" * 32
  3442. data["contexts"]["trace"]["status"] = "ok"
  3443. transaction_1 = self.store_event(data, project_id=self.project.id)
  3444. data = self.transaction_data.copy()
  3445. data["event_id"] = "b" * 32
  3446. data["contexts"]["trace"]["status"] = "aborted"
  3447. transaction_2 = self.store_event(data, project_id=self.project.id)
  3448. data = self.transaction_data.copy()
  3449. data["event_id"] = "c" * 32
  3450. data["contexts"]["trace"]["status"] = "already_exists"
  3451. transaction_3 = self.store_event(data, project_id=self.project.id)
  3452. self.run_test_in_query(
  3453. "transaction.status:[aborted, already_exists]",
  3454. [transaction_2, transaction_3],
  3455. [transaction_1],
  3456. )
  3457. def test_messed_up_function_values(self):
  3458. # TODO (evanh): It would be nice if this surfaced an error to the user.
  3459. # The problem: The && causes the parser to treat that term not as a bad
  3460. # function call but a valid raw search with parens in it. It's not trivial
  3461. # to change the parser to recognize "bad function values" and surface them.
  3462. for v in ["a", "b"]:
  3463. self.store_event(
  3464. data={
  3465. "event_id": v * 32,
  3466. "timestamp": self.ten_mins_ago,
  3467. "fingerprint": ["group_1"],
  3468. },
  3469. project_id=self.project.id,
  3470. )
  3471. features = {"organizations:discover-basic": True, "organizations:global-views": True}
  3472. query = {
  3473. "field": [
  3474. "transaction",
  3475. "project",
  3476. "epm()",
  3477. "p50()",
  3478. "p95()",
  3479. "failure_rate()",
  3480. "apdex(300)",
  3481. "count_unique(user)",
  3482. "user_misery(300)",
  3483. "count_miserable(user, 300)",
  3484. ],
  3485. "query": "failure_rate():>0.003&& users:>10 event.type:transaction",
  3486. "sort": "-failure_rate",
  3487. "statsPeriod": "24h",
  3488. }
  3489. response = self.do_request(query, features=features)
  3490. assert response.status_code == 200, response.content
  3491. data = response.data["data"]
  3492. assert len(data) == 0
  3493. def test_context_fields_between_datasets(self):
  3494. event_data = self.load_data(platform="android")
  3495. transaction_data = self.load_data()
  3496. event_data["spans"] = transaction_data["spans"]
  3497. event_data["contexts"]["trace"] = transaction_data["contexts"]["trace"]
  3498. event_data["type"] = "transaction"
  3499. event_data["transaction"] = "/failure_rate/1"
  3500. event_data["timestamp"] = iso_format(before_now(minutes=10))
  3501. event_data["start_timestamp"] = iso_format(before_now(minutes=10, seconds=5))
  3502. event_data["user"]["geo"] = {"country_code": "US", "region": "CA", "city": "San Francisco"}
  3503. self.store_event(event_data, project_id=self.project.id)
  3504. event_data["type"] = "error"
  3505. self.store_event(event_data, project_id=self.project.id)
  3506. fields = [
  3507. "os.build",
  3508. "os.kernel_version",
  3509. "device.arch",
  3510. # TODO: battery level is not consistent across both datasets
  3511. # "device.battery_level",
  3512. "device.brand",
  3513. "device.charging",
  3514. "device.locale",
  3515. "device.model_id",
  3516. "device.name",
  3517. "device.online",
  3518. "device.orientation",
  3519. "device.simulator",
  3520. "device.uuid",
  3521. ]
  3522. data = [
  3523. {"field": fields + ["location", "count()"], "query": "event.type:error"},
  3524. {"field": fields + ["duration", "count()"], "query": "event.type:transaction"},
  3525. ]
  3526. for datum in data:
  3527. response = self.do_request(datum)
  3528. assert response.status_code == 200, response.content
  3529. assert len(response.data["data"]) == 1, datum
  3530. results = response.data["data"]
  3531. assert results[0]["count()"] == 1, datum
  3532. for field in fields:
  3533. key, value = field.split(".", 1)
  3534. expected = str(event_data["contexts"][key][value])
  3535. assert results[0][field] == expected, field + str(datum)
  3536. def test_http_fields_between_datasets(self):
  3537. event_data = self.load_data(platform="android")
  3538. transaction_data = self.load_data()
  3539. event_data["spans"] = transaction_data["spans"]
  3540. event_data["contexts"]["trace"] = transaction_data["contexts"]["trace"]
  3541. event_data["type"] = "transaction"
  3542. event_data["transaction"] = "/failure_rate/1"
  3543. event_data["timestamp"] = iso_format(before_now(minutes=10))
  3544. event_data["start_timestamp"] = iso_format(before_now(minutes=10, seconds=5))
  3545. event_data["user"]["geo"] = {"country_code": "US", "region": "CA", "city": "San Francisco"}
  3546. event_data["request"] = transaction_data["request"]
  3547. self.store_event(event_data, project_id=self.project.id)
  3548. event_data["type"] = "error"
  3549. self.store_event(event_data, project_id=self.project.id)
  3550. fields = ["http.method", "http.referer", "http.url"]
  3551. expected = ["GET", "fixtures.transaction", "http://countries:8010/country_by_code/"]
  3552. data = [
  3553. {"field": fields + ["location", "count()"], "query": "event.type:error"},
  3554. {"field": fields + ["duration", "count()"], "query": "event.type:transaction"},
  3555. ]
  3556. for datum in data:
  3557. response = self.do_request(datum)
  3558. assert response.status_code == 200, response.content
  3559. assert len(response.data["data"]) == 1, datum
  3560. results = response.data["data"]
  3561. assert results[0]["count()"] == 1, datum
  3562. for (field, exp) in zip(fields, expected):
  3563. assert results[0][field] == exp, field + str(datum)
  3564. def test_failure_count_alias_field(self):
  3565. data = self.transaction_data.copy()
  3566. data["transaction"] = "/failure_count/success"
  3567. self.store_event(data, project_id=self.project.id)
  3568. data = self.transaction_data.copy()
  3569. data["transaction"] = "/failure_count/unknown"
  3570. data["contexts"]["trace"]["status"] = "unknown_error"
  3571. self.store_event(data, project_id=self.project.id)
  3572. for i in range(6):
  3573. data = self.transaction_data.copy()
  3574. data["transaction"] = f"/failure_count/{i}"
  3575. data["contexts"]["trace"]["status"] = "unauthenticated"
  3576. self.store_event(data, project_id=self.project.id)
  3577. query = {"field": ["count()", "failure_count()"], "query": "event.type:transaction"}
  3578. response = self.do_request(query)
  3579. assert response.status_code == 200, response.content
  3580. assert len(response.data["data"]) == 1
  3581. data = response.data["data"]
  3582. assert data[0]["count()"] == 8
  3583. assert data[0]["failure_count()"] == 6
  3584. @mock.patch("sentry.utils.snuba.quantize_time")
  3585. def test_quantize_dates(self, mock_quantize):
  3586. self.create_project()
  3587. mock_quantize.return_value = before_now(days=1).replace(tzinfo=utc)
  3588. # Don't quantize short time periods
  3589. query = {"statsPeriod": "1h", "query": "", "field": ["id", "timestamp"]}
  3590. self.do_request(query)
  3591. # Don't quantize absolute date periods
  3592. self.do_request(query)
  3593. query = {
  3594. "start": iso_format(before_now(days=20)),
  3595. "end": iso_format(before_now(days=15)),
  3596. "query": "",
  3597. "field": ["id", "timestamp"],
  3598. }
  3599. self.do_request(query)
  3600. assert len(mock_quantize.mock_calls) == 0
  3601. # Quantize long date periods
  3602. query = {"field": ["id", "timestamp"], "statsPeriod": "90d", "query": ""}
  3603. self.do_request(query)
  3604. assert len(mock_quantize.mock_calls) == 2
  3605. @mock.patch("sentry.snuba.discover.query")
  3606. def test_valid_referrer(self, mock):
  3607. mock.return_value = {}
  3608. query = {
  3609. "field": ["user"],
  3610. "referrer": "api.performance.transaction-summary",
  3611. "project": [self.project.id],
  3612. }
  3613. self.do_request(query)
  3614. _, kwargs = mock.call_args
  3615. self.assertEqual(kwargs["referrer"], "api.performance.transaction-summary")
  3616. @mock.patch("sentry.snuba.discover.query")
  3617. def test_invalid_referrer(self, mock):
  3618. mock.return_value = {}
  3619. query = {
  3620. "field": ["user"],
  3621. "referrer": "api.performance.invalid",
  3622. "project": [self.project.id],
  3623. }
  3624. self.do_request(query)
  3625. _, kwargs = mock.call_args
  3626. self.assertEqual(kwargs["referrer"], self.referrer)
  3627. @mock.patch("sentry.snuba.discover.query")
  3628. def test_empty_referrer(self, mock):
  3629. mock.return_value = {}
  3630. query = {
  3631. "field": ["user"],
  3632. "project": [self.project.id],
  3633. }
  3634. self.do_request(query)
  3635. _, kwargs = mock.call_args
  3636. self.assertEqual(kwargs["referrer"], self.referrer)
  3637. @mock.patch("sentry.snuba.discover.query")
  3638. def test_api_token_referrer(self, mock):
  3639. mock.return_value = {}
  3640. # Project ID cannot be inferred when using an org API key, so that must
  3641. # be passed in the parameters
  3642. api_key = ApiKey.objects.create(organization=self.organization, scope_list=["org:read"])
  3643. query = {
  3644. "field": ["project.name", "environment"],
  3645. "project": [self.project.id],
  3646. }
  3647. features = {"organizations:discover-basic": True}
  3648. features.update(self.features)
  3649. url = self.reverse_url()
  3650. with self.feature(features):
  3651. self.client_get(
  3652. url,
  3653. query,
  3654. format="json",
  3655. HTTP_AUTHORIZATION=b"Basic " + b64encode(f"{api_key.key}:".encode()),
  3656. )
  3657. _, kwargs = mock.call_args
  3658. self.assertEqual(kwargs["referrer"], "api.auth-token.events")
  3659. def test_limit_number_of_fields(self):
  3660. self.create_project()
  3661. for i in range(1, 25):
  3662. response = self.do_request({"field": ["id"] * i})
  3663. if i <= 20:
  3664. assert response.status_code == 200
  3665. else:
  3666. assert response.status_code == 400
  3667. assert (
  3668. response.data["detail"]
  3669. == "You can view up to 20 fields at a time. Please delete some and try again."
  3670. )
  3671. def test_percentile_function_meta_types(self):
  3672. self.store_event(self.transaction_data, project_id=self.project.id)
  3673. query = {
  3674. "field": [
  3675. "transaction",
  3676. "percentile(transaction.duration, 0.95)",
  3677. "percentile(measurements.fp, 0.95)",
  3678. "percentile(measurements.fcp, 0.95)",
  3679. "percentile(measurements.lcp, 0.95)",
  3680. "percentile(measurements.fid, 0.95)",
  3681. "percentile(measurements.ttfb, 0.95)",
  3682. "percentile(measurements.ttfb.requesttime, 0.95)",
  3683. "percentile(measurements.cls, 0.95)",
  3684. "percentile(measurements.foo, 0.95)",
  3685. "percentile(measurements.bar, 0.95)",
  3686. ],
  3687. "query": "",
  3688. "orderby": ["transaction"],
  3689. }
  3690. response = self.do_request(query)
  3691. assert response.status_code == 200, response.content
  3692. meta = response.data["meta"]["fields"]
  3693. assert meta["percentile(transaction.duration, 0.95)"] == "duration"
  3694. assert meta["percentile(measurements.fp, 0.95)"] == "duration"
  3695. assert meta["percentile(measurements.fcp, 0.95)"] == "duration"
  3696. assert meta["percentile(measurements.lcp, 0.95)"] == "duration"
  3697. assert meta["percentile(measurements.fid, 0.95)"] == "duration"
  3698. assert meta["percentile(measurements.ttfb, 0.95)"] == "duration"
  3699. assert meta["percentile(measurements.ttfb.requesttime, 0.95)"] == "duration"
  3700. assert meta["percentile(measurements.cls, 0.95)"] == "number"
  3701. assert meta["percentile(measurements.foo, 0.95)"] == "number"
  3702. assert meta["percentile(measurements.bar, 0.95)"] == "number"
  3703. units = response.data["meta"]["units"]
  3704. assert units["percentile(transaction.duration, 0.95)"] == "millisecond"
  3705. assert units["percentile(measurements.fp, 0.95)"] == "millisecond"
  3706. assert units["percentile(measurements.fcp, 0.95)"] == "millisecond"
  3707. assert units["percentile(measurements.lcp, 0.95)"] == "millisecond"
  3708. assert units["percentile(measurements.fid, 0.95)"] == "millisecond"
  3709. assert units["percentile(measurements.ttfb, 0.95)"] == "millisecond"
  3710. assert units["percentile(measurements.ttfb.requesttime, 0.95)"] == "millisecond"
  3711. def test_count_at_least_query(self):
  3712. self.store_event(self.transaction_data, self.project.id)
  3713. response = self.do_request({"field": "count_at_least(measurements.fcp, 0)"})
  3714. assert response.status_code == 200
  3715. assert len(response.data["data"]) == 1
  3716. assert response.data["data"][0]["count_at_least(measurements.fcp, 0)"] == 1
  3717. # a value that's a little bigger than the stored fcp
  3718. fcp = int(self.transaction_data["measurements"]["fcp"]["value"] + 1)
  3719. response = self.do_request({"field": f"count_at_least(measurements.fcp, {fcp})"})
  3720. assert response.status_code == 200
  3721. assert len(response.data["data"]) == 1
  3722. assert response.data["data"][0][f"count_at_least(measurements.fcp, {fcp})"] == 0
  3723. def test_measurements_query(self):
  3724. self.store_event(self.transaction_data, self.project.id)
  3725. query = {
  3726. "field": [
  3727. "measurements.fp",
  3728. "measurements.fcp",
  3729. "measurements.lcp",
  3730. "measurements.fid",
  3731. ]
  3732. }
  3733. response = self.do_request(query)
  3734. assert response.status_code == 200, response.content
  3735. assert len(response.data["data"]) == 1
  3736. for field in query["field"]:
  3737. measure = field.split(".", 1)[1]
  3738. assert (
  3739. response.data["data"][0][field]
  3740. == self.transaction_data["measurements"][measure]["value"]
  3741. )
  3742. query = {
  3743. "field": [
  3744. "measurements.fP",
  3745. "measurements.Fcp",
  3746. "measurements.LcP",
  3747. "measurements.FID",
  3748. ]
  3749. }
  3750. response = self.do_request(query)
  3751. assert response.status_code == 200, response.content
  3752. assert len(response.data["data"]) == 1
  3753. for field in query["field"]:
  3754. measure = field.split(".", 1)[1].lower()
  3755. assert (
  3756. response.data["data"][0][field]
  3757. == self.transaction_data["measurements"][measure]["value"]
  3758. )
  3759. def test_measurements_aggregations(self):
  3760. self.store_event(self.transaction_data, self.project.id)
  3761. # should try all the potential aggregates
  3762. # Skipped tests for stddev and var since sampling one data point
  3763. # results in nan.
  3764. query = {
  3765. "field": [
  3766. "percentile(measurements.fcp, 0.5)",
  3767. "count_unique(measurements.fcp)",
  3768. "min(measurements.fcp)",
  3769. "max(measurements.fcp)",
  3770. "avg(measurements.fcp)",
  3771. "sum(measurements.fcp)",
  3772. ],
  3773. }
  3774. response = self.do_request(query)
  3775. assert response.status_code == 200, response.content
  3776. assert len(response.data["data"]) == 1
  3777. assert (
  3778. response.data["data"][0]["percentile(measurements.fcp, 0.5)"]
  3779. == self.transaction_data["measurements"]["fcp"]["value"]
  3780. )
  3781. assert response.data["data"][0]["count_unique(measurements.fcp)"] == 1
  3782. assert (
  3783. response.data["data"][0]["min(measurements.fcp)"]
  3784. == self.transaction_data["measurements"]["fcp"]["value"]
  3785. )
  3786. assert (
  3787. response.data["data"][0]["max(measurements.fcp)"]
  3788. == self.transaction_data["measurements"]["fcp"]["value"]
  3789. )
  3790. assert (
  3791. response.data["data"][0]["avg(measurements.fcp)"]
  3792. == self.transaction_data["measurements"]["fcp"]["value"]
  3793. )
  3794. assert (
  3795. response.data["data"][0]["sum(measurements.fcp)"]
  3796. == self.transaction_data["measurements"]["fcp"]["value"]
  3797. )
  3798. def get_measurement_condition_response(self, query_str, field):
  3799. query = {
  3800. "field": ["transaction", "count()"] + (field if field else []),
  3801. "query": query_str,
  3802. }
  3803. response = self.do_request(query)
  3804. assert response.status_code == 200, response.content
  3805. return response
  3806. def assert_measurement_condition_without_results(self, query_str, field=None):
  3807. response = self.get_measurement_condition_response(query_str, field)
  3808. assert len(response.data["data"]) == 0
  3809. def assert_measurement_condition_with_results(self, query_str, field=None):
  3810. response = self.get_measurement_condition_response(query_str, field)
  3811. assert len(response.data["data"]) == 1
  3812. assert response.data["data"][0]["transaction"] == self.transaction_data["metadata"]["title"]
  3813. assert response.data["data"][0]["count()"] == 1
  3814. def test_measurements_conditions(self):
  3815. self.store_event(self.transaction_data, self.project.id)
  3816. fcp = self.transaction_data["measurements"]["fcp"]["value"]
  3817. # equality condition
  3818. # We use json dumps here to ensure precision when converting from float to str
  3819. # This is necessary because equality on floating point values need to be precise
  3820. self.assert_measurement_condition_with_results(f"measurements.fcp:{json.dumps(fcp)}")
  3821. # greater than condition
  3822. self.assert_measurement_condition_with_results(f"measurements.fcp:>{fcp - 1}")
  3823. self.assert_measurement_condition_without_results(f"measurements.fcp:>{fcp + 1}")
  3824. # less than condition
  3825. self.assert_measurement_condition_with_results(f"measurements.fcp:<{fcp + 1}")
  3826. self.assert_measurement_condition_without_results(f"measurements.fcp:<{fcp - 1}")
  3827. # has condition
  3828. self.assert_measurement_condition_with_results("has:measurements.fcp")
  3829. self.assert_measurement_condition_without_results("!has:measurements.fcp")
  3830. def test_measurements_aggregation_conditions(self):
  3831. self.store_event(self.transaction_data, self.project.id)
  3832. fcp = self.transaction_data["measurements"]["fcp"]["value"]
  3833. functions = [
  3834. "percentile(measurements.fcp, 0.5)",
  3835. "min(measurements.fcp)",
  3836. "max(measurements.fcp)",
  3837. "avg(measurements.fcp)",
  3838. "sum(measurements.fcp)",
  3839. ]
  3840. for function in functions:
  3841. self.assert_measurement_condition_with_results(
  3842. f"{function}:>{fcp - 1}", field=[function]
  3843. )
  3844. self.assert_measurement_condition_without_results(
  3845. f"{function}:>{fcp + 1}", field=[function]
  3846. )
  3847. self.assert_measurement_condition_with_results(
  3848. f"{function}:<{fcp + 1}", field=[function]
  3849. )
  3850. self.assert_measurement_condition_without_results(
  3851. f"{function}:<{fcp - 1}", field=[function]
  3852. )
  3853. count_unique = "count_unique(measurements.fcp)"
  3854. self.assert_measurement_condition_with_results(f"{count_unique}:1", field=[count_unique])
  3855. self.assert_measurement_condition_without_results(f"{count_unique}:0", field=[count_unique])
  3856. def test_compare_numeric_aggregate(self):
  3857. self.store_event(self.transaction_data, self.project.id)
  3858. query = {
  3859. "field": [
  3860. "p75(measurements.fcp)",
  3861. "compare_numeric_aggregate(p75_measurements_fcp,greater,0)",
  3862. ],
  3863. }
  3864. response = self.do_request(query)
  3865. assert response.status_code == 200, response.content
  3866. assert len(response.data["data"]) == 1
  3867. assert (
  3868. response.data["data"][0]["compare_numeric_aggregate(p75_measurements_fcp,greater,0)"]
  3869. == 1
  3870. )
  3871. query = {
  3872. "field": ["p75()", "compare_numeric_aggregate(p75,equals,0)"],
  3873. }
  3874. response = self.do_request(query)
  3875. assert response.status_code == 200, response.content
  3876. assert len(response.data["data"]) == 1
  3877. assert response.data["data"][0]["compare_numeric_aggregate(p75,equals,0)"] == 0
  3878. def test_no_team_key_transactions(self):
  3879. transactions = [
  3880. "/blah_transaction/",
  3881. "/foo_transaction/",
  3882. "/zoo_transaction/",
  3883. ]
  3884. for transaction in transactions:
  3885. self.transaction_data["transaction"] = transaction
  3886. self.store_event(self.transaction_data, self.project.id)
  3887. query = {
  3888. "team": "myteams",
  3889. "project": [self.project.id],
  3890. # use the order by to ensure the result order
  3891. "orderby": "transaction",
  3892. "field": [
  3893. "team_key_transaction",
  3894. "transaction",
  3895. "transaction.status",
  3896. "project",
  3897. "epm()",
  3898. "failure_rate()",
  3899. "percentile(transaction.duration, 0.95)",
  3900. ],
  3901. }
  3902. response = self.do_request(query)
  3903. assert response.status_code == 200, response.content
  3904. data = response.data["data"]
  3905. assert len(data) == 3
  3906. assert data[0]["team_key_transaction"] == 0
  3907. assert data[0]["transaction"] == "/blah_transaction/"
  3908. assert data[1]["team_key_transaction"] == 0
  3909. assert data[1]["transaction"] == "/foo_transaction/"
  3910. assert data[2]["team_key_transaction"] == 0
  3911. assert data[2]["transaction"] == "/zoo_transaction/"
  3912. def test_team_key_transactions_my_teams(self):
  3913. team1 = self.create_team(organization=self.organization, name="Team A")
  3914. self.create_team_membership(team1, user=self.user)
  3915. self.project.add_team(team1)
  3916. team2 = self.create_team(organization=self.organization, name="Team B")
  3917. self.project.add_team(team2)
  3918. transactions = ["/blah_transaction/"]
  3919. key_transactions = [
  3920. (team1, "/foo_transaction/"),
  3921. (team2, "/zoo_transaction/"),
  3922. ]
  3923. for transaction in transactions:
  3924. self.transaction_data["transaction"] = transaction
  3925. self.store_event(self.transaction_data, self.project.id)
  3926. for team, transaction in key_transactions:
  3927. self.transaction_data["transaction"] = transaction
  3928. self.store_event(self.transaction_data, self.project.id)
  3929. TeamKeyTransaction.objects.create(
  3930. organization=self.organization,
  3931. transaction=transaction,
  3932. project_team=ProjectTeam.objects.get(project=self.project, team=team),
  3933. )
  3934. query = {
  3935. "team": "myteams",
  3936. "project": [self.project.id],
  3937. "field": [
  3938. "team_key_transaction",
  3939. "transaction",
  3940. "transaction.status",
  3941. "project",
  3942. "epm()",
  3943. "failure_rate()",
  3944. "percentile(transaction.duration, 0.95)",
  3945. ],
  3946. }
  3947. query["orderby"] = ["team_key_transaction", "transaction"]
  3948. response = self.do_request(query)
  3949. assert response.status_code == 200, response.content
  3950. data = response.data["data"]
  3951. assert len(data) == 3
  3952. assert data[0]["team_key_transaction"] == 0
  3953. assert data[0]["transaction"] == "/blah_transaction/"
  3954. assert data[1]["team_key_transaction"] == 0
  3955. assert data[1]["transaction"] == "/zoo_transaction/"
  3956. assert data[2]["team_key_transaction"] == 1
  3957. assert data[2]["transaction"] == "/foo_transaction/"
  3958. # not specifying any teams should use my teams
  3959. query = {
  3960. "project": [self.project.id],
  3961. "field": [
  3962. "team_key_transaction",
  3963. "transaction",
  3964. "transaction.status",
  3965. "project",
  3966. "epm()",
  3967. "failure_rate()",
  3968. "percentile(transaction.duration, 0.95)",
  3969. ],
  3970. }
  3971. query["orderby"] = ["team_key_transaction", "transaction"]
  3972. response = self.do_request(query)
  3973. assert response.status_code == 200, response.content
  3974. data = response.data["data"]
  3975. assert len(data) == 3
  3976. assert data[0]["team_key_transaction"] == 0
  3977. assert data[0]["transaction"] == "/blah_transaction/"
  3978. assert data[1]["team_key_transaction"] == 0
  3979. assert data[1]["transaction"] == "/zoo_transaction/"
  3980. assert data[2]["team_key_transaction"] == 1
  3981. assert data[2]["transaction"] == "/foo_transaction/"
  3982. def test_team_key_transactions_orderby(self):
  3983. team1 = self.create_team(organization=self.organization, name="Team A")
  3984. team2 = self.create_team(organization=self.organization, name="Team B")
  3985. transactions = ["/blah_transaction/"]
  3986. key_transactions = [
  3987. (team1, "/foo_transaction/"),
  3988. (team2, "/zoo_transaction/"),
  3989. ]
  3990. for transaction in transactions:
  3991. self.transaction_data["transaction"] = transaction
  3992. self.store_event(self.transaction_data, self.project.id)
  3993. for team, transaction in key_transactions:
  3994. self.create_team_membership(team, user=self.user)
  3995. self.project.add_team(team)
  3996. self.transaction_data["transaction"] = transaction
  3997. self.store_event(self.transaction_data, self.project.id)
  3998. TeamKeyTransaction.objects.create(
  3999. organization=self.organization,
  4000. transaction=transaction,
  4001. project_team=ProjectTeam.objects.get(project=self.project, team=team),
  4002. )
  4003. query = {
  4004. "team": "myteams",
  4005. "project": [self.project.id],
  4006. "field": [
  4007. "team_key_transaction",
  4008. "transaction",
  4009. "transaction.status",
  4010. "project",
  4011. "epm()",
  4012. "failure_rate()",
  4013. "percentile(transaction.duration, 0.95)",
  4014. ],
  4015. }
  4016. # test ascending order
  4017. query["orderby"] = ["team_key_transaction", "transaction"]
  4018. response = self.do_request(query)
  4019. assert response.status_code == 200, response.content
  4020. data = response.data["data"]
  4021. assert len(data) == 3
  4022. assert data[0]["team_key_transaction"] == 0
  4023. assert data[0]["transaction"] == "/blah_transaction/"
  4024. assert data[1]["team_key_transaction"] == 1
  4025. assert data[1]["transaction"] == "/foo_transaction/"
  4026. assert data[2]["team_key_transaction"] == 1
  4027. assert data[2]["transaction"] == "/zoo_transaction/"
  4028. # test descending order
  4029. query["orderby"] = ["-team_key_transaction", "-transaction"]
  4030. response = self.do_request(query)
  4031. assert response.status_code == 200, response.content
  4032. data = response.data["data"]
  4033. assert len(data) == 3
  4034. assert data[0]["team_key_transaction"] == 1
  4035. assert data[0]["transaction"] == "/zoo_transaction/"
  4036. assert data[1]["team_key_transaction"] == 1
  4037. assert data[1]["transaction"] == "/foo_transaction/"
  4038. assert data[2]["team_key_transaction"] == 0
  4039. assert data[2]["transaction"] == "/blah_transaction/"
  4040. def test_team_key_transactions_query(self):
  4041. team1 = self.create_team(organization=self.organization, name="Team A")
  4042. team2 = self.create_team(organization=self.organization, name="Team B")
  4043. transactions = ["/blah_transaction/"]
  4044. key_transactions = [
  4045. (team1, "/foo_transaction/"),
  4046. (team2, "/zoo_transaction/"),
  4047. ]
  4048. for transaction in transactions:
  4049. self.transaction_data["transaction"] = transaction
  4050. self.store_event(self.transaction_data, self.project.id)
  4051. for team, transaction in key_transactions:
  4052. self.create_team_membership(team, user=self.user)
  4053. self.project.add_team(team)
  4054. self.transaction_data["transaction"] = transaction
  4055. self.store_event(self.transaction_data, self.project.id)
  4056. TeamKeyTransaction.objects.create(
  4057. organization=self.organization,
  4058. project_team=ProjectTeam.objects.get(
  4059. project=self.project,
  4060. team=team,
  4061. ),
  4062. transaction=transaction,
  4063. )
  4064. query = {
  4065. "team": "myteams",
  4066. "project": [self.project.id],
  4067. # use the order by to ensure the result order
  4068. "orderby": "transaction",
  4069. "field": [
  4070. "team_key_transaction",
  4071. "transaction",
  4072. "transaction.status",
  4073. "project",
  4074. "epm()",
  4075. "failure_rate()",
  4076. "percentile(transaction.duration, 0.95)",
  4077. ],
  4078. }
  4079. # key transactions
  4080. query["query"] = "has:team_key_transaction"
  4081. response = self.do_request(query)
  4082. assert response.status_code == 200, response.content
  4083. data = response.data["data"]
  4084. assert len(data) == 2
  4085. assert data[0]["team_key_transaction"] == 1
  4086. assert data[0]["transaction"] == "/foo_transaction/"
  4087. assert data[1]["team_key_transaction"] == 1
  4088. assert data[1]["transaction"] == "/zoo_transaction/"
  4089. # key transactions
  4090. query["query"] = "team_key_transaction:true"
  4091. response = self.do_request(query)
  4092. assert response.status_code == 200, response.content
  4093. data = response.data["data"]
  4094. assert len(data) == 2
  4095. assert data[0]["team_key_transaction"] == 1
  4096. assert data[0]["transaction"] == "/foo_transaction/"
  4097. assert data[1]["team_key_transaction"] == 1
  4098. assert data[1]["transaction"] == "/zoo_transaction/"
  4099. # not key transactions
  4100. query["query"] = "!has:team_key_transaction"
  4101. response = self.do_request(query)
  4102. assert response.status_code == 200, response.content
  4103. data = response.data["data"]
  4104. assert len(data) == 1
  4105. assert data[0]["team_key_transaction"] == 0
  4106. assert data[0]["transaction"] == "/blah_transaction/"
  4107. # not key transactions
  4108. query["query"] = "team_key_transaction:false"
  4109. response = self.do_request(query)
  4110. assert response.status_code == 200, response.content
  4111. data = response.data["data"]
  4112. assert len(data) == 1
  4113. assert data[0]["team_key_transaction"] == 0
  4114. assert data[0]["transaction"] == "/blah_transaction/"
  4115. def test_too_many_team_key_transactions(self):
  4116. MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS = 1
  4117. with mock.patch(
  4118. "sentry.search.events.fields.MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS",
  4119. MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS,
  4120. ):
  4121. team = self.create_team(organization=self.organization, name="Team A")
  4122. self.create_team_membership(team, user=self.user)
  4123. self.project.add_team(team)
  4124. project_team = ProjectTeam.objects.get(project=self.project, team=team)
  4125. for i in range(MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS + 1):
  4126. transaction = f"transaction-{team.id}-{i}"
  4127. self.transaction_data["transaction"] = transaction
  4128. self.store_event(self.transaction_data, self.project.id)
  4129. TeamKeyTransaction.objects.bulk_create(
  4130. [
  4131. TeamKeyTransaction(
  4132. organization=self.organization,
  4133. project_team=project_team,
  4134. transaction=f"transaction-{team.id}-{i}",
  4135. )
  4136. for i in range(MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS + 1)
  4137. ]
  4138. )
  4139. query = {
  4140. "team": "myteams",
  4141. "project": [self.project.id],
  4142. "orderby": "transaction",
  4143. "field": [
  4144. "team_key_transaction",
  4145. "transaction",
  4146. "transaction.status",
  4147. "project",
  4148. "epm()",
  4149. "failure_rate()",
  4150. "percentile(transaction.duration, 0.95)",
  4151. ],
  4152. }
  4153. response = self.do_request(query)
  4154. assert response.status_code == 200, response.content
  4155. data = response.data["data"]
  4156. assert len(data) == 2
  4157. assert (
  4158. sum(row["team_key_transaction"] for row in data)
  4159. == MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS
  4160. )
  4161. def test_no_pagination_param(self):
  4162. self.store_event(
  4163. data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago, "fingerprint": ["group1"]},
  4164. project_id=self.project.id,
  4165. )
  4166. query = {"field": ["id", "project.id"], "project": [self.project.id], "noPagination": True}
  4167. response = self.do_request(query)
  4168. assert response.status_code == 200
  4169. assert len(response.data["data"]) == 1
  4170. assert "Link" not in response
  4171. def test_nan_result(self):
  4172. query = {"field": ["apdex(300)"], "project": [self.project.id], "query": f"id:{'0' * 32}"}
  4173. response = self.do_request(query)
  4174. assert response.status_code == 200
  4175. assert len(response.data["data"]) == 1
  4176. assert response.data["data"][0]["apdex(300)"] == 0
  4177. def test_equation_simple(self):
  4178. event_data = self.load_data(
  4179. timestamp=before_now(minutes=10),
  4180. )
  4181. event_data["breakdowns"]["span_ops"]["ops.http"]["value"] = 1500
  4182. self.store_event(data=event_data, project_id=self.project.id)
  4183. query = {
  4184. "field": ["spans.http", "equation|spans.http / 3"],
  4185. "project": [self.project.id],
  4186. "query": "event.type:transaction",
  4187. }
  4188. response = self.do_request(
  4189. query,
  4190. {
  4191. "organizations:discover-basic": True,
  4192. },
  4193. )
  4194. assert response.status_code == 200, response.content
  4195. assert len(response.data["data"]) == 1
  4196. assert (
  4197. response.data["data"][0]["equation|spans.http / 3"]
  4198. == event_data["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
  4199. )
  4200. assert response.data["meta"]["fields"]["equation|spans.http / 3"] == "number"
  4201. def test_equation_sort(self):
  4202. event_data = self.transaction_data.copy()
  4203. event_data["breakdowns"] = {"span_ops": {"ops.http": {"value": 1500}}}
  4204. self.store_event(data=event_data, project_id=self.project.id)
  4205. event_data2 = self.transaction_data.copy()
  4206. event_data2["breakdowns"] = {"span_ops": {"ops.http": {"value": 2000}}}
  4207. self.store_event(data=event_data2, project_id=self.project.id)
  4208. query = {
  4209. "field": ["spans.http", "equation|spans.http / 3"],
  4210. "project": [self.project.id],
  4211. "orderby": "equation|spans.http / 3",
  4212. "query": "event.type:transaction",
  4213. }
  4214. response = self.do_request(
  4215. query,
  4216. {
  4217. "organizations:discover-basic": True,
  4218. },
  4219. )
  4220. assert response.status_code == 200, response.content
  4221. assert len(response.data["data"]) == 2
  4222. assert (
  4223. response.data["data"][0]["equation|spans.http / 3"]
  4224. == event_data["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
  4225. )
  4226. assert (
  4227. response.data["data"][1]["equation|spans.http / 3"]
  4228. == event_data2["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
  4229. )
  4230. def test_equation_operation_limit(self):
  4231. query = {
  4232. "field": ["spans.http", f"equation|spans.http{' * 2' * 11}"],
  4233. "project": [self.project.id],
  4234. "query": "event.type:transaction",
  4235. }
  4236. response = self.do_request(
  4237. query,
  4238. {
  4239. "organizations:discover-basic": True,
  4240. },
  4241. )
  4242. assert response.status_code == 400
  4243. @mock.patch("sentry.api.bases.organization_events.MAX_FIELDS", 2)
  4244. def test_equation_field_limit(self):
  4245. query = {
  4246. "field": ["spans.http", "transaction.duration", "equation|5 * 2"],
  4247. "project": [self.project.id],
  4248. "query": "event.type:transaction",
  4249. }
  4250. response = self.do_request(
  4251. query,
  4252. {
  4253. "organizations:discover-basic": True,
  4254. },
  4255. )
  4256. assert response.status_code == 400
  4257. def test_count_if(self):
  4258. unicode_phrase1 = "\u716e\u6211\u66f4\u591a\u7684\u98df\u7269\uff0c\u6211\u9913\u4e86"
  4259. for i in range(5):
  4260. data = self.load_data(
  4261. timestamp=before_now(minutes=(10 + i)),
  4262. duration=timedelta(milliseconds=100 if i < 3 else 200),
  4263. )
  4264. data["tags"] = {
  4265. "sub_customer.is-Enterprise-42": "yes" if i == 0 else "no",
  4266. "unicode-phrase": unicode_phrase1 if i == 0 else "no",
  4267. }
  4268. self.store_event(data, project_id=self.project.id)
  4269. query = {
  4270. "field": [
  4271. "count_if(transaction.duration, less, 150)",
  4272. "count_if(transaction.duration, greater, 150)",
  4273. "count_if(sub_customer.is-Enterprise-42, equals, yes)",
  4274. "count_if(sub_customer.is-Enterprise-42, notEquals, yes)",
  4275. f"count_if(unicode-phrase, equals, {unicode_phrase1})",
  4276. ],
  4277. "project": [self.project.id],
  4278. }
  4279. response = self.do_request(query)
  4280. assert response.status_code == 200
  4281. assert len(response.data["data"]) == 1
  4282. assert response.data["data"][0]["count_if(transaction.duration, less, 150)"] == 3
  4283. assert response.data["data"][0]["count_if(transaction.duration, greater, 150)"] == 2
  4284. assert response.data["data"][0]["count_if(sub_customer.is-Enterprise-42, equals, yes)"] == 1
  4285. assert (
  4286. response.data["data"][0]["count_if(sub_customer.is-Enterprise-42, notEquals, yes)"] == 4
  4287. )
  4288. assert response.data["data"][0][f"count_if(unicode-phrase, equals, {unicode_phrase1})"] == 1
  4289. def test_count_if_measurements_cls(self):
  4290. data = self.transaction_data.copy()
  4291. data["measurements"] = {"cls": {"value": 0.5}}
  4292. self.store_event(data, project_id=self.project.id)
  4293. data["measurements"] = {"cls": {"value": 0.1}}
  4294. self.store_event(data, project_id=self.project.id)
  4295. query = {
  4296. "field": [
  4297. "count_if(measurements.cls, greater, 0.05)",
  4298. "count_if(measurements.cls, less, 0.3)",
  4299. ],
  4300. "project": [self.project.id],
  4301. }
  4302. response = self.do_request(query)
  4303. assert response.status_code == 200
  4304. assert len(response.data["data"]) == 1
  4305. assert response.data["data"][0]["count_if(measurements.cls, greater, 0.05)"] == 2
  4306. assert response.data["data"][0]["count_if(measurements.cls, less, 0.3)"] == 1
  4307. def test_count_if_filter(self):
  4308. for i in range(5):
  4309. data = self.load_data(
  4310. timestamp=before_now(minutes=(10 + i)),
  4311. duration=timedelta(milliseconds=100 if i < 3 else 200),
  4312. )
  4313. data["tags"] = {"sub_customer.is-Enterprise-42": "yes" if i == 0 else "no"}
  4314. self.store_event(data, project_id=self.project.id)
  4315. query = {
  4316. "field": [
  4317. "count_if(transaction.duration, less, 150)",
  4318. ],
  4319. "query": "count_if(transaction.duration, less, 150):>2",
  4320. "project": [self.project.id],
  4321. }
  4322. response = self.do_request(query)
  4323. assert response.status_code == 200
  4324. assert len(response.data["data"]) == 1
  4325. assert response.data["data"][0]["count_if(transaction.duration, less, 150)"] == 3
  4326. query = {
  4327. "field": [
  4328. "count_if(transaction.duration, less, 150)",
  4329. ],
  4330. "query": "count_if(transaction.duration, less, 150):<2",
  4331. "project": [self.project.id],
  4332. }
  4333. response = self.do_request(query)
  4334. assert response.status_code == 200
  4335. assert len(response.data["data"]) == 0
  4336. def test_filters_with_escaped_asterisk(self):
  4337. self.transaction_data["transaction"] = r"/:a*/:b-:c(\d\.\e+)"
  4338. self.store_event(self.transaction_data, project_id=self.project.id)
  4339. query = {
  4340. "field": ["transaction", "transaction.duration"],
  4341. # make sure to escape the asterisk so it's not treated as a wildcard
  4342. "query": r'transaction:"/:a\*/:b-:c(\d\.\e+)"',
  4343. "project": [self.project.id],
  4344. }
  4345. response = self.do_request(query)
  4346. assert response.status_code == 200
  4347. assert len(response.data["data"]) == 1
  4348. def test_filters_with_back_slashes(self):
  4349. self.transaction_data["transaction"] = r"a\b\c@d"
  4350. self.store_event(self.transaction_data, project_id=self.project.id)
  4351. query = {
  4352. "field": ["transaction", "transaction.duration"],
  4353. "query": r'transaction:"a\b\c@d"',
  4354. "project": [self.project.id],
  4355. }
  4356. response = self.do_request(query)
  4357. assert response.status_code == 200
  4358. assert len(response.data["data"]) == 1
  4359. def test_mobile_measurements(self):
  4360. self.transaction_data["measurements"]["frames_total"] = {"value": 100}
  4361. self.transaction_data["measurements"]["frames_slow"] = {"value": 10}
  4362. self.transaction_data["measurements"]["frames_frozen"] = {"value": 5}
  4363. self.transaction_data["measurements"]["stall_count"] = {"value": 2}
  4364. self.transaction_data["measurements"]["stall_total_time"] = {"value": 12}
  4365. self.transaction_data["measurements"]["stall_longest_time"] = {"value": 7}
  4366. self.store_event(self.transaction_data, project_id=self.project.id)
  4367. query = {
  4368. "field": [
  4369. "measurements.frames_total",
  4370. "measurements.frames_slow",
  4371. "measurements.frames_frozen",
  4372. "measurements.frames_slow_rate",
  4373. "measurements.frames_frozen_rate",
  4374. "measurements.stall_count",
  4375. "measurements.stall_total_time",
  4376. "measurements.stall_longest_time",
  4377. "measurements.stall_percentage",
  4378. ],
  4379. "query": "",
  4380. "project": [self.project.id],
  4381. }
  4382. response = self.do_request(query)
  4383. assert response.status_code == 200
  4384. data = response.data["data"]
  4385. assert len(data) == 1
  4386. assert data[0]["measurements.frames_total"] == 100
  4387. assert data[0]["measurements.frames_slow"] == 10
  4388. assert data[0]["measurements.frames_frozen"] == 5
  4389. assert data[0]["measurements.frames_slow_rate"] == 0.1
  4390. assert data[0]["measurements.frames_frozen_rate"] == 0.05
  4391. assert data[0]["measurements.stall_count"] == 2
  4392. assert data[0]["measurements.stall_total_time"] == 12
  4393. assert data[0]["measurements.stall_longest_time"] == 7
  4394. assert data[0]["measurements.stall_percentage"] == 0.004
  4395. meta = response.data["meta"]["fields"]
  4396. assert meta["measurements.frames_total"] == "number"
  4397. assert meta["measurements.frames_slow"] == "number"
  4398. assert meta["measurements.frames_frozen"] == "number"
  4399. assert meta["measurements.frames_slow_rate"] == "percentage"
  4400. assert meta["measurements.frames_frozen_rate"] == "percentage"
  4401. assert meta["measurements.stall_count"] == "number"
  4402. assert meta["measurements.stall_total_time"] == "number"
  4403. assert meta["measurements.stall_longest_time"] == "number"
  4404. assert meta["measurements.stall_percentage"] == "percentage"
  4405. query = {
  4406. "field": [
  4407. "p75(measurements.frames_slow_rate)",
  4408. "p75(measurements.frames_frozen_rate)",
  4409. "percentile(measurements.frames_slow_rate,0.5)",
  4410. "percentile(measurements.frames_frozen_rate,0.5)",
  4411. "p75(measurements.stall_percentage)",
  4412. "percentile(measurements.stall_percentage,0.5)",
  4413. ],
  4414. "query": "",
  4415. "project": [self.project.id],
  4416. }
  4417. response = self.do_request(query)
  4418. assert response.status_code == 200
  4419. data = response.data["data"]
  4420. assert len(data) == 1
  4421. assert data[0]["p75(measurements.frames_slow_rate)"] == 0.1
  4422. assert data[0]["p75(measurements.frames_frozen_rate)"] == 0.05
  4423. assert data[0]["p75(measurements.stall_percentage)"] == 0.004
  4424. assert data[0]["percentile(measurements.frames_slow_rate,0.5)"] == 0.1
  4425. assert data[0]["percentile(measurements.frames_frozen_rate,0.5)"] == 0.05
  4426. assert data[0]["percentile(measurements.stall_percentage,0.5)"] == 0.004
  4427. meta = response.data["meta"]["fields"]
  4428. assert meta["p75(measurements.frames_slow_rate)"] == "percentage"
  4429. assert meta["p75(measurements.frames_frozen_rate)"] == "percentage"
  4430. assert meta["p75(measurements.stall_percentage)"] == "percentage"
  4431. assert meta["percentile(measurements.frames_slow_rate,0.5)"] == "percentage"
  4432. assert meta["percentile(measurements.stall_percentage,0.5)"] == "percentage"
  4433. def test_project_auto_fields(self):
  4434. self.store_event(
  4435. data={"event_id": "a" * 32, "environment": "staging", "timestamp": self.ten_mins_ago},
  4436. project_id=self.project.id,
  4437. )
  4438. query = {"field": ["environment"]}
  4439. response = self.do_request(query)
  4440. assert response.status_code == 200, response.content
  4441. assert len(response.data["data"]) == 1
  4442. assert response.data["data"][0]["environment"] == "staging"
  4443. assert response.data["data"][0]["project.name"] == self.project.slug
  4444. def test_timestamp_different_from_params(self):
  4445. fifteen_days_ago = iso_format(before_now(days=15))
  4446. fifteen_days_later = iso_format(before_now(days=-15))
  4447. for query_text in [
  4448. f"timestamp:<{fifteen_days_ago}",
  4449. f"timestamp:<={fifteen_days_ago}",
  4450. f"timestamp:>{fifteen_days_later}",
  4451. f"timestamp:>={fifteen_days_later}",
  4452. ]:
  4453. query = {
  4454. "field": ["count()"],
  4455. "query": query_text,
  4456. "statsPeriod": "14d",
  4457. "project": self.project.id,
  4458. }
  4459. response = self.do_request(query)
  4460. assert response.status_code == 400, query_text
  4461. @mock.patch("sentry.search.events.builder.raw_snql_query")
  4462. def test_removes_unnecessary_default_project_and_transaction_thresholds(self, mock_snql_query):
  4463. mock_snql_query.side_effect = [{"meta": {}, "data": []}]
  4464. ProjectTransactionThreshold.objects.create(
  4465. project=self.project,
  4466. organization=self.organization,
  4467. # these are the default values that we use
  4468. threshold=constants.DEFAULT_PROJECT_THRESHOLD,
  4469. metric=TransactionMetric.DURATION.value,
  4470. )
  4471. ProjectTransactionThresholdOverride.objects.create(
  4472. transaction="transaction",
  4473. project=self.project,
  4474. organization=self.organization,
  4475. # these are the default values that we use
  4476. threshold=constants.DEFAULT_PROJECT_THRESHOLD,
  4477. metric=TransactionMetric.DURATION.value,
  4478. )
  4479. query = {
  4480. "field": ["apdex()", "user_misery()"],
  4481. "query": "event.type:transaction",
  4482. "project": [self.project.id],
  4483. }
  4484. response = self.do_request(
  4485. query,
  4486. features={
  4487. "organizations:discover-basic": True,
  4488. "organizations:global-views": True,
  4489. },
  4490. )
  4491. assert response.status_code == 200, response.content
  4492. assert mock_snql_query.call_count == 1
  4493. assert (
  4494. Function("tuple", ["duration", 300], "project_threshold_config")
  4495. in mock_snql_query.call_args_list[0][0][0].query.select
  4496. )
  4497. @mock.patch("sentry.search.events.builder.raw_snql_query")
  4498. def test_removes_unnecessary_default_project_and_transaction_thresholds_keeps_others(
  4499. self, mock_snql_query
  4500. ):
  4501. mock_snql_query.side_effect = [{"meta": {}, "data": []}]
  4502. ProjectTransactionThreshold.objects.create(
  4503. project=self.project,
  4504. organization=self.organization,
  4505. # these are the default values that we use
  4506. threshold=constants.DEFAULT_PROJECT_THRESHOLD,
  4507. metric=TransactionMetric.DURATION.value,
  4508. )
  4509. ProjectTransactionThresholdOverride.objects.create(
  4510. transaction="transaction",
  4511. project=self.project,
  4512. organization=self.organization,
  4513. # these are the default values that we use
  4514. threshold=constants.DEFAULT_PROJECT_THRESHOLD,
  4515. metric=TransactionMetric.DURATION.value,
  4516. )
  4517. project = self.create_project()
  4518. ProjectTransactionThreshold.objects.create(
  4519. project=project,
  4520. organization=self.organization,
  4521. threshold=100,
  4522. metric=TransactionMetric.LCP.value,
  4523. )
  4524. ProjectTransactionThresholdOverride.objects.create(
  4525. transaction="transaction",
  4526. project=project,
  4527. organization=self.organization,
  4528. threshold=200,
  4529. metric=TransactionMetric.LCP.value,
  4530. )
  4531. query = {
  4532. "field": ["apdex()", "user_misery()"],
  4533. "query": "event.type:transaction",
  4534. "project": [self.project.id, project.id],
  4535. }
  4536. response = self.do_request(
  4537. query,
  4538. features={
  4539. "organizations:discover-basic": True,
  4540. "organizations:global-views": True,
  4541. },
  4542. )
  4543. assert response.status_code == 200, response.content
  4544. assert mock_snql_query.call_count == 1
  4545. project_threshold_override_config_index = Function(
  4546. "indexOf",
  4547. [
  4548. # only 1 transaction override is present here
  4549. # because the other use to the default values
  4550. [(Function("toUInt64", [project.id]), "transaction")],
  4551. (Column("project_id"), Column("transaction")),
  4552. ],
  4553. "project_threshold_override_config_index",
  4554. )
  4555. project_threshold_config_index = Function(
  4556. "indexOf",
  4557. [
  4558. # only 1 project override is present here
  4559. # because the other use to the default values
  4560. [Function("toUInt64", [project.id])],
  4561. Column("project_id"),
  4562. ],
  4563. "project_threshold_config_index",
  4564. )
  4565. assert (
  4566. Function(
  4567. "if",
  4568. [
  4569. Function("equals", [project_threshold_override_config_index, 0]),
  4570. Function(
  4571. "if",
  4572. [
  4573. Function("equals", [project_threshold_config_index, 0]),
  4574. ("duration", 300),
  4575. Function(
  4576. "arrayElement", [[("lcp", 100)], project_threshold_config_index]
  4577. ),
  4578. ],
  4579. ),
  4580. Function(
  4581. "arrayElement",
  4582. [[("lcp", 200)], project_threshold_override_config_index],
  4583. ),
  4584. ],
  4585. "project_threshold_config",
  4586. )
  4587. in mock_snql_query.call_args_list[0][0][0].query.select
  4588. )
  4589. def test_count_web_vitals(self):
  4590. # Good
  4591. self.transaction_data["measurements"] = {
  4592. "lcp": {"value": constants.VITAL_THRESHOLDS["lcp"]["meh"] - 100},
  4593. }
  4594. self.store_event(self.transaction_data, self.project.id)
  4595. # Meh
  4596. self.transaction_data["measurements"] = {
  4597. "lcp": {"value": constants.VITAL_THRESHOLDS["lcp"]["meh"] + 100},
  4598. }
  4599. self.store_event(self.transaction_data, self.project.id)
  4600. self.store_event(self.transaction_data, self.project.id)
  4601. query = {
  4602. "field": [
  4603. "count_web_vitals(measurements.lcp, poor)",
  4604. "count_web_vitals(measurements.lcp, meh)",
  4605. "count_web_vitals(measurements.lcp, good)",
  4606. ]
  4607. }
  4608. response = self.do_request(query)
  4609. assert response.status_code == 200, response.content
  4610. assert len(response.data["data"]) == 1
  4611. assert response.data["data"][0] == {
  4612. "count_web_vitals(measurements.lcp, poor)": 0,
  4613. "count_web_vitals(measurements.lcp, meh)": 2,
  4614. "count_web_vitals(measurements.lcp, good)": 1,
  4615. }
  4616. def test_count_web_vitals_invalid_vital(self):
  4617. query = {
  4618. "field": [
  4619. "count_web_vitals(measurements.foo, poor)",
  4620. ],
  4621. "project": [self.project.id],
  4622. }
  4623. response = self.do_request(query)
  4624. assert response.status_code == 400, response.content
  4625. query = {
  4626. "field": [
  4627. "count_web_vitals(tags[lcp], poor)",
  4628. ],
  4629. "project": [self.project.id],
  4630. }
  4631. response = self.do_request(query)
  4632. assert response.status_code == 400, response.content
  4633. query = {
  4634. "field": [
  4635. "count_web_vitals(transaction.duration, poor)",
  4636. ],
  4637. "project": [self.project.id],
  4638. }
  4639. response = self.do_request(query)
  4640. assert response.status_code == 400, response.content
  4641. query = {
  4642. "field": [
  4643. "count_web_vitals(measurements.lcp, bad)",
  4644. ],
  4645. "project": [self.project.id],
  4646. }
  4647. response = self.do_request(query)
  4648. assert response.status_code == 400, response.content
  4649. def test_tag_that_looks_like_aggregate(self):
  4650. data = self.load_data(
  4651. timestamp=before_now(minutes=1),
  4652. )
  4653. data["tags"] = {"p95": "<5k"}
  4654. self.store_event(data, project_id=self.project.id)
  4655. query = {
  4656. "field": ["p95"],
  4657. "query": "p95:<5k",
  4658. "project": [self.project.id],
  4659. }
  4660. response = self.do_request(query)
  4661. assert response.status_code == 200, response.content
  4662. data = response.data["data"]
  4663. assert len(data) == 1
  4664. assert data[0]["p95"] == "<5k"
  4665. def test_chained_or_query_meta_tip(self):
  4666. query = {
  4667. "field": ["transaction"],
  4668. "query": "transaction:a OR transaction:b",
  4669. "project": [self.project.id],
  4670. }
  4671. response = self.do_request(query)
  4672. assert response.status_code == 200, response.content
  4673. meta = response.data["meta"]
  4674. assert meta["tips"] == {
  4675. "query": "Did you know you can replace chained or conditions like `field:a OR field:b OR field:c` with `field:[a,b,c]`",
  4676. "columns": None,
  4677. }
  4678. @override_settings(SENTRY_SELF_HOSTED=False)
  4679. def test_ratelimit(self):
  4680. query = {
  4681. "field": ["transaction"],
  4682. "project": [self.project.id],
  4683. }
  4684. with freeze_time("2000-01-01"):
  4685. for _ in range(15):
  4686. self.do_request(query, features={"organizations:discover-events-rate-limit": True})
  4687. response = self.do_request(
  4688. query, features={"organizations:discover-events-rate-limit": True}
  4689. )
  4690. assert response.status_code == 429, response.content
  4691. @override_settings(SENTRY_SELF_HOSTED=False)
  4692. def test_no_ratelimit(self):
  4693. query = {
  4694. "field": ["transaction"],
  4695. "project": [self.project.id],
  4696. }
  4697. with freeze_time("2000-01-01"):
  4698. for _ in range(15):
  4699. self.do_request(query)
  4700. response = self.do_request(query)
  4701. assert response.status_code == 200, response.content
  4702. def test_transaction_source(self):
  4703. query = {
  4704. "field": ["transaction"],
  4705. "query": "transaction.source:task",
  4706. "project": [self.project.id],
  4707. }
  4708. response = self.do_request(query)
  4709. assert response.status_code == 200, response.content