test_unmerge.py 21 KB

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