test_unmerge.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. from __future__ import annotations
  2. import functools
  3. import hashlib
  4. import itertools
  5. import logging
  6. import uuid
  7. from datetime import datetime, timedelta, timezone
  8. from unittest.mock import patch
  9. import pytz
  10. from sentry import eventstream, tagstore, tsdb
  11. from sentry.eventstore.models import Event
  12. from sentry.models import Environment, Group, GroupHash, GroupRelease, Release, UserReport
  13. from sentry.similarity import _make_index_backend, features
  14. from sentry.tasks.merge import merge_groups
  15. from sentry.tasks.unmerge import (
  16. get_caches,
  17. get_event_user_from_interface,
  18. get_fingerprint,
  19. get_group_backfill_attributes,
  20. get_group_creation_attributes,
  21. unmerge,
  22. )
  23. from sentry.testutils.cases import SnubaTestCase, TestCase
  24. from sentry.testutils.helpers.datetime import before_now, iso_format
  25. from sentry.testutils.helpers.features import with_feature
  26. from sentry.tsdb.base import TSDBModel
  27. from sentry.utils import redis
  28. from sentry.utils.dates import to_timestamp
  29. # Use the default redis client as a cluster client in the similarity index
  30. index = _make_index_backend(redis.clusters.get("default").get_local_client(0))
  31. @patch("sentry.similarity.features.index", new=index)
  32. class UnmergeTestCase(TestCase, SnubaTestCase):
  33. def test_get_fingerprint(self):
  34. assert (
  35. get_fingerprint(
  36. self.store_event(data={"message": "Hello world"}, project_id=self.project.id)
  37. )
  38. == hashlib.md5(b"Hello world").hexdigest()
  39. )
  40. assert (
  41. get_fingerprint(
  42. self.store_event(
  43. data={"message": "Hello world", "fingerprint": ["Not hello world"]},
  44. project_id=self.project.id,
  45. )
  46. )
  47. == hashlib.md5(b"Not hello world").hexdigest()
  48. )
  49. def test_get_group_creation_attributes(self):
  50. now = datetime.utcnow().replace(microsecond=0, tzinfo=timezone.utc)
  51. e1 = self.store_event(
  52. data={
  53. "fingerprint": ["group1"],
  54. "platform": "javascript",
  55. "message": "Hello from JavaScript",
  56. "type": "default",
  57. "level": "info",
  58. "tags": {"logger": "javascript"},
  59. "timestamp": iso_format(now),
  60. },
  61. project_id=self.project.id,
  62. )
  63. e2 = self.store_event(
  64. data={
  65. "fingerprint": ["group1"],
  66. "platform": "python",
  67. "message": "Hello from Python",
  68. "type": "default",
  69. "level": "error",
  70. "tags": {"logger": "python"},
  71. "timestamp": iso_format(now),
  72. },
  73. project_id=self.project.id,
  74. )
  75. e3 = self.store_event(
  76. data={
  77. "fingerprint": ["group1"],
  78. "platform": "java",
  79. "message": "Hello from Java",
  80. "type": "default",
  81. "level": "debug",
  82. "tags": {"logger": "java"},
  83. "timestamp": iso_format(now),
  84. },
  85. project_id=self.project.id,
  86. )
  87. events = [e1, e2, e3]
  88. assert get_group_creation_attributes(get_caches(), events) == {
  89. "active_at": now,
  90. "first_seen": now,
  91. "last_seen": now,
  92. "platform": "java",
  93. "message": "Hello from JavaScript",
  94. "level": logging.INFO,
  95. "score": Group.calculate_score(3, now),
  96. "logger": "java",
  97. "times_seen": 3,
  98. "first_release": None,
  99. "culprit": "",
  100. "data": {
  101. "type": "default",
  102. "last_received": e1.data["received"],
  103. "metadata": {"title": "Hello from JavaScript"},
  104. },
  105. }
  106. def test_get_group_backfill_attributes(self):
  107. now = datetime.utcnow().replace(microsecond=0, tzinfo=timezone.utc)
  108. assert get_group_backfill_attributes(
  109. get_caches(),
  110. Group(
  111. active_at=now,
  112. first_seen=now,
  113. last_seen=now,
  114. platform="javascript",
  115. message="Hello from JavaScript",
  116. level=logging.INFO,
  117. score=Group.calculate_score(3, now),
  118. logger="javascript",
  119. times_seen=1,
  120. first_release=None,
  121. culprit="",
  122. data={"type": "default", "last_received": to_timestamp(now), "metadata": {}},
  123. ),
  124. [
  125. self.store_event(
  126. data={
  127. "platform": "python",
  128. "message": "Hello from Python",
  129. "timestamp": iso_format(now - timedelta(hours=1)),
  130. "type": "default",
  131. "level": "debug",
  132. "tags": {"logger": "java"},
  133. },
  134. project_id=self.project.id,
  135. ),
  136. self.store_event(
  137. data={
  138. "platform": "java",
  139. "message": "Hello from Java",
  140. "timestamp": iso_format(now - timedelta(hours=2)),
  141. "type": "default",
  142. "level": "debug",
  143. "tags": {"logger": "java"},
  144. },
  145. project_id=self.project.id,
  146. ),
  147. ],
  148. ) == {
  149. "active_at": now - timedelta(hours=2),
  150. "first_seen": now - timedelta(hours=2),
  151. "platform": "java",
  152. "score": Group.calculate_score(3, now),
  153. "logger": "java",
  154. "times_seen": 3,
  155. "first_release": None,
  156. }
  157. @with_feature("projects:similarity-indexing")
  158. def test_unmerge(self):
  159. now = before_now(minutes=5).replace(microsecond=0, tzinfo=pytz.utc)
  160. def time_from_now(offset=0):
  161. return now + timedelta(seconds=offset)
  162. project = self.create_project()
  163. sequence = itertools.count(0)
  164. tag_values = itertools.cycle(["red", "green", "blue"])
  165. user_values = itertools.cycle([{"id": 1}, {"id": 2}])
  166. def create_message_event(
  167. template, parameters, environment, release, fingerprint="group1"
  168. ) -> Event:
  169. i = next(sequence)
  170. event_id = uuid.UUID(fields=(i, 0x0, 0x1000, 0x80, 0x80, 0x808080808080)).hex
  171. tags = [["color", next(tag_values)]]
  172. if release:
  173. tags.append(["sentry:release", release])
  174. event = self.store_event(
  175. data={
  176. "event_id": event_id,
  177. "message": template % parameters,
  178. "type": "default",
  179. "user": next(user_values),
  180. "tags": tags,
  181. "fingerprint": [fingerprint],
  182. "timestamp": iso_format(now + timedelta(seconds=i)),
  183. "environment": environment,
  184. "release": release,
  185. },
  186. project_id=project.id,
  187. )
  188. UserReport.objects.create(
  189. project_id=project.id,
  190. group_id=event.group.id,
  191. event_id=event_id,
  192. name="Log Hat",
  193. email="ceo@corptron.com",
  194. comments="Quack",
  195. )
  196. features.record([event])
  197. return event
  198. events: dict[str | None, list[Event]] = {}
  199. for event in (
  200. create_message_event(
  201. "This is message #%s.", i, environment="production", release="version"
  202. )
  203. for i in range(10)
  204. ):
  205. events.setdefault(get_fingerprint(event), []).append(event)
  206. for event in (
  207. create_message_event(
  208. "This is message #%s!",
  209. i,
  210. environment="production",
  211. release="version2",
  212. fingerprint="group2",
  213. )
  214. for i in range(10, 16)
  215. ):
  216. events.setdefault(get_fingerprint(event), []).append(event)
  217. event = create_message_event(
  218. "This is message #%s!",
  219. 17,
  220. environment="staging",
  221. release="version3",
  222. fingerprint="group3",
  223. )
  224. events.setdefault(get_fingerprint(event), []).append(event)
  225. merge_source, source, destination = list(Group.objects.all())
  226. assert len(events) == 3
  227. assert sum(len(x) for x in events.values()) == 17
  228. production_environment = Environment.objects.get(
  229. organization_id=project.organization_id, name="production"
  230. )
  231. with self.tasks():
  232. eventstream_state = eventstream.backend.start_merge(
  233. project.id, [merge_source.id], source.id
  234. )
  235. merge_groups.delay([merge_source.id], source.id)
  236. eventstream.backend.end_merge(eventstream_state)
  237. assert {
  238. (gtv.value, gtv.times_seen)
  239. for gtv in tagstore.backend.get_group_tag_values(
  240. source,
  241. production_environment.id,
  242. "color",
  243. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  244. )
  245. } == {("red", 6), ("green", 5), ("blue", 5)}
  246. similar_items = features.compare(source)
  247. assert len(similar_items) == 2
  248. assert similar_items[0][0] == source.id
  249. assert similar_items[0][1]["message:message:character-shingles"] == 1.0
  250. assert similar_items[1][0] == destination.id
  251. assert similar_items[1][1]["message:message:character-shingles"] < 1.0
  252. with self.tasks():
  253. unmerge.delay(
  254. project.id, source.id, destination.id, [list(events.keys())[0]], None, batch_size=5
  255. )
  256. assert (
  257. list(
  258. Group.objects.filter(id=merge_source.id).values_list(
  259. "times_seen", "first_seen", "last_seen"
  260. )
  261. )
  262. == []
  263. )
  264. assert list(
  265. Group.objects.filter(id=source.id).values_list("times_seen", "first_seen", "last_seen")
  266. ) == [(6, time_from_now(10), time_from_now(15))]
  267. assert list(
  268. Group.objects.filter(id=destination.id).values_list(
  269. "times_seen", "first_seen", "last_seen"
  270. )
  271. ) == [(11, time_from_now(0), time_from_now(16))]
  272. assert source.id != destination.id
  273. assert source.project == destination.project
  274. destination_event_ids = set(map(lambda event: event.event_id, list(events.values())[1]))
  275. assert destination_event_ids == set(
  276. UserReport.objects.filter(group_id=source.id).values_list("event_id", flat=True)
  277. )
  278. assert list(
  279. GroupHash.objects.filter(group_id=source.id).values_list("hash", flat=True)
  280. ) == [list(events.keys())[1]]
  281. assert set(
  282. GroupRelease.objects.filter(group_id=source.id).values_list(
  283. "environment", "first_seen", "last_seen"
  284. )
  285. ) == {("production", time_from_now(10), time_from_now(15))}
  286. assert {
  287. (gtv.value, gtv.times_seen)
  288. for gtv in tagstore.backend.get_group_tag_values(
  289. destination,
  290. production_environment.id,
  291. "color",
  292. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  293. )
  294. } == {("red", 4), ("green", 3), ("blue", 3)}
  295. destination_event_ids = set(
  296. map(lambda event: event.event_id, list(events.values())[0] + list(events.values())[2])
  297. )
  298. assert destination_event_ids == set(
  299. UserReport.objects.filter(group_id=destination.id).values_list("event_id", flat=True)
  300. )
  301. assert set(
  302. GroupHash.objects.filter(group_id=destination.id).values_list("hash", flat=True)
  303. ) == {list(events.keys())[0], list(events.keys())[2]}
  304. assert set(
  305. GroupRelease.objects.filter(group_id=destination.id).values_list(
  306. "environment", "first_seen", "last_seen"
  307. )
  308. ) == {
  309. ("production", time_from_now(0), time_from_now(9)),
  310. ("staging", time_from_now(16), time_from_now(16)),
  311. }
  312. assert {
  313. (gtk.value, gtk.times_seen)
  314. for gtk in tagstore.backend.get_group_tag_values(
  315. destination,
  316. production_environment.id,
  317. "color",
  318. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  319. )
  320. } == {("red", 4), ("blue", 3), ("green", 3)}
  321. rollup_duration = 3600
  322. time_series = tsdb.backend.get_range(
  323. TSDBModel.group,
  324. [source.id, destination.id],
  325. now - timedelta(seconds=rollup_duration),
  326. time_from_now(17),
  327. rollup_duration,
  328. tenant_ids={"referrer": "get_range", "organization_id": 1},
  329. )
  330. environment_time_series = tsdb.backend.get_range(
  331. TSDBModel.group,
  332. [source.id, destination.id],
  333. now - timedelta(seconds=rollup_duration),
  334. time_from_now(17),
  335. rollup_duration,
  336. environment_ids=[production_environment.id],
  337. tenant_ids={"referrer": "get_range", "organization_id": 1},
  338. )
  339. def get_expected_series_values(rollup, events, function=None):
  340. if function is None:
  341. def function(aggregate, event):
  342. return (aggregate if aggregate is not None else 0) + 1
  343. expected: dict[float, float] = {}
  344. for event in events:
  345. k = float((to_timestamp(event.datetime) // rollup_duration) * rollup_duration)
  346. expected[k] = function(expected.get(k), event)
  347. return expected
  348. def assert_series_contains(expected, actual, default=0):
  349. actual = dict(actual)
  350. for key, value in expected.items():
  351. assert actual.get(key, 0) == value
  352. for key in set(actual.keys()) - set(expected.keys()):
  353. assert actual.get(key, 0) == default
  354. assert_series_contains(
  355. get_expected_series_values(rollup_duration, list(events.values())[1]),
  356. time_series[source.id],
  357. 0,
  358. )
  359. assert_series_contains(
  360. get_expected_series_values(
  361. rollup_duration, list(events.values())[0] + list(events.values())[2]
  362. ),
  363. time_series[destination.id],
  364. 0,
  365. )
  366. assert_series_contains(
  367. get_expected_series_values(rollup_duration, list(events.values())[1]),
  368. environment_time_series[source.id],
  369. 0,
  370. )
  371. assert_series_contains(
  372. get_expected_series_values(
  373. rollup_duration, list(events.values())[0][:-1] + list(events.values())[2]
  374. ),
  375. environment_time_series[destination.id],
  376. 0,
  377. )
  378. time_series = tsdb.backend.get_distinct_counts_series(
  379. TSDBModel.users_affected_by_group,
  380. [source.id, destination.id],
  381. now - timedelta(seconds=rollup_duration),
  382. time_from_now(17),
  383. rollup_duration,
  384. tenant_ids={"referrer": "r", "organization_id": 1234},
  385. )
  386. environment_time_series = tsdb.backend.get_distinct_counts_series(
  387. TSDBModel.users_affected_by_group,
  388. [source.id, destination.id],
  389. now - timedelta(seconds=rollup_duration),
  390. time_from_now(17),
  391. rollup_duration,
  392. environment_id=production_environment.id,
  393. tenant_ids={"referrer": "r", "organization_id": 1234},
  394. )
  395. def collect_by_user_tag(aggregate, event):
  396. aggregate = aggregate if aggregate is not None else set()
  397. aggregate.add(get_event_user_from_interface(event.data["user"]).tag_value)
  398. return aggregate
  399. for series in [time_series, environment_time_series]:
  400. assert_series_contains(
  401. {
  402. timestamp: len(values)
  403. for timestamp, values in get_expected_series_values(
  404. rollup_duration, list(events.values())[1], collect_by_user_tag
  405. ).items()
  406. },
  407. series[source.id],
  408. )
  409. assert_series_contains(
  410. {
  411. timestamp: len(values)
  412. for timestamp, values in get_expected_series_values(
  413. rollup_duration,
  414. list(events.values())[0] + list(events.values())[2],
  415. collect_by_user_tag,
  416. ).items()
  417. },
  418. time_series[destination.id],
  419. )
  420. def strip_zeroes(data):
  421. for group_id, series in data.items():
  422. for _, values in series:
  423. for key, val in list(values.items()):
  424. if val == 0:
  425. values.pop(key)
  426. return data
  427. def collect_by_release(group, aggregate, event):
  428. aggregate = aggregate if aggregate is not None else {}
  429. release = event.get_tag("sentry:release")
  430. if not release:
  431. return aggregate
  432. release = GroupRelease.objects.get(
  433. group_id=group.id,
  434. environment=event.data["environment"],
  435. release_id=Release.objects.get(
  436. organization_id=project.organization_id, version=release
  437. ).id,
  438. ).id
  439. aggregate[release] = aggregate.get(release, 0) + 1
  440. return aggregate
  441. items = {}
  442. for i in [source.id, destination.id]:
  443. items[i] = list(GroupRelease.objects.filter(group_id=i).values_list("id", flat=True))
  444. time_series = strip_zeroes(
  445. tsdb.backend.get_frequency_series(
  446. TSDBModel.frequent_releases_by_group,
  447. items,
  448. now - timedelta(seconds=rollup_duration),
  449. time_from_now(17),
  450. rollup_duration,
  451. tenant_ids={"referrer": "r", "organization_id": 1234},
  452. )
  453. )
  454. assert_series_contains(
  455. get_expected_series_values(
  456. rollup_duration,
  457. list(events.values())[1],
  458. functools.partial(collect_by_release, source),
  459. ),
  460. time_series[source.id],
  461. {},
  462. )
  463. assert_series_contains(
  464. get_expected_series_values(
  465. rollup_duration,
  466. list(events.values())[0] + list(events.values())[2],
  467. functools.partial(collect_by_release, destination),
  468. ),
  469. time_series[destination.id],
  470. {},
  471. )
  472. items = {}
  473. for i in [source.id, destination.id]:
  474. items[i] = list(Environment.objects.all().values_list("id", flat=True))
  475. time_series = strip_zeroes(
  476. tsdb.backend.get_frequency_series(
  477. TSDBModel.frequent_environments_by_group,
  478. items,
  479. now - timedelta(seconds=rollup_duration),
  480. time_from_now(17),
  481. rollup_duration,
  482. tenant_ids={"referrer": "r", "organization_id": 1234},
  483. )
  484. )
  485. def collect_by_environment(aggregate, event):
  486. aggregate = aggregate if aggregate is not None else {}
  487. environment = Environment.objects.get(
  488. organization_id=project.organization_id, name=event.data["environment"]
  489. ).id
  490. aggregate[environment] = aggregate.get(environment, 0) + 1
  491. return aggregate
  492. assert_series_contains(
  493. get_expected_series_values(
  494. rollup_duration, list(events.values())[1], collect_by_environment
  495. ),
  496. time_series[source.id],
  497. {},
  498. )
  499. assert_series_contains(
  500. get_expected_series_values(
  501. rollup_duration,
  502. list(events.values())[0] + list(events.values())[2],
  503. collect_by_environment,
  504. ),
  505. time_series[destination.id],
  506. {},
  507. )
  508. source_similar_items = features.compare(source)
  509. assert source_similar_items[0] == (
  510. source.id,
  511. {
  512. "exception:message:character-shingles": None,
  513. "exception:stacktrace:application-chunks": None,
  514. "exception:stacktrace:pairs": None,
  515. "message:message:character-shingles": 1.0,
  516. },
  517. )
  518. assert source_similar_items[1][0] == destination.id
  519. assert source_similar_items[1][1]["message:message:character-shingles"] < 1.0
  520. destination_similar_items = features.compare(destination)
  521. assert destination_similar_items[0] == (
  522. destination.id,
  523. {
  524. "exception:message:character-shingles": None,
  525. "exception:stacktrace:application-chunks": None,
  526. "exception:stacktrace:pairs": None,
  527. "message:message:character-shingles": 1.0,
  528. },
  529. )
  530. assert destination_similar_items[1][0] == source.id
  531. assert destination_similar_items[1][1]["message:message:character-shingles"] < 1.0