test_organization_events.py 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316
  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
  4710. @mock.patch("sentry.search.events.builder.raw_snql_query")
  4711. def test_profiles_dataset_simple(self, mock_snql_query):
  4712. mock_snql_query.side_effect = [{"meta": {}, "data": []}]
  4713. query = {
  4714. "field": [
  4715. "project",
  4716. "transaction",
  4717. "last_seen()",
  4718. "latest_event()",
  4719. "count()",
  4720. "count_unique(transaction)",
  4721. "percentile(profile.duration, 0.25)",
  4722. "p50(profile.duration)",
  4723. "p75(profile.duration)",
  4724. "p95(profile.duration)",
  4725. "p99(profile.duration)",
  4726. "p100(profile.duration)",
  4727. "min(profile.duration)",
  4728. "max(profile.duration)",
  4729. "avg(profile.duration)",
  4730. "sum(profile.duration)",
  4731. ],
  4732. "project": [self.project.id],
  4733. "dataset": "profiles",
  4734. }
  4735. response = self.do_request(query, features={"organizations:profiling": True})
  4736. assert response.status_code == 200, response.content