test_unmerge.py 21 KB

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