test_unmerge.py 21 KB

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