test_unmerge.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import functools
  2. import hashlib
  3. import itertools
  4. import logging
  5. import uuid
  6. from datetime import datetime, timedelta
  7. from unittest.mock import patch
  8. import pytz
  9. from django.utils import timezone
  10. from sentry import eventstream, tagstore, tsdb
  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 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=pytz.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(template, parameters, environment, release, fingerprint="group1"):
  166. i = next(sequence)
  167. event_id = uuid.UUID(fields=(i, 0x0, 0x1000, 0x80, 0x80, 0x808080808080)).hex
  168. tags = [["color", next(tag_values)]]
  169. if release:
  170. tags.append(["sentry:release", release])
  171. event = self.store_event(
  172. data={
  173. "event_id": event_id,
  174. "message": template % parameters,
  175. "type": "default",
  176. "user": next(user_values),
  177. "tags": tags,
  178. "fingerprint": [fingerprint],
  179. "timestamp": iso_format(now + timedelta(seconds=i)),
  180. "environment": environment,
  181. "release": release,
  182. },
  183. project_id=project.id,
  184. )
  185. UserReport.objects.create(
  186. project_id=project.id,
  187. group_id=event.group.id,
  188. event_id=event_id,
  189. name="Log Hat",
  190. email="ceo@corptron.com",
  191. comments="Quack",
  192. )
  193. features.record([event])
  194. return event
  195. events = {}
  196. for event in (
  197. create_message_event(
  198. "This is message #%s.", i, environment="production", release="version"
  199. )
  200. for i in range(10)
  201. ):
  202. events.setdefault(get_fingerprint(event), []).append(event)
  203. for event in (
  204. create_message_event(
  205. "This is message #%s!",
  206. i,
  207. environment="production",
  208. release="version2",
  209. fingerprint="group2",
  210. )
  211. for i in range(10, 16)
  212. ):
  213. events.setdefault(get_fingerprint(event), []).append(event)
  214. event = create_message_event(
  215. "This is message #%s!",
  216. 17,
  217. environment="staging",
  218. release="version3",
  219. fingerprint="group3",
  220. )
  221. events.setdefault(get_fingerprint(event), []).append(event)
  222. merge_source, source, destination = list(Group.objects.all())
  223. assert len(events) == 3
  224. assert sum(map(len, events.values())) == 17
  225. production_environment = Environment.objects.get(
  226. organization_id=project.organization_id, name="production"
  227. )
  228. with self.tasks():
  229. eventstream_state = eventstream.backend.start_merge(
  230. project.id, [merge_source.id], source.id
  231. )
  232. merge_groups.delay([merge_source.id], source.id)
  233. eventstream.backend.end_merge(eventstream_state)
  234. assert {
  235. (gtv.value, gtv.times_seen)
  236. for gtv in tagstore.get_group_tag_values(
  237. source,
  238. production_environment.id,
  239. "color",
  240. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  241. )
  242. } == {("red", 6), ("green", 5), ("blue", 5)}
  243. similar_items = features.compare(source)
  244. assert len(similar_items) == 2
  245. assert similar_items[0][0] == source.id
  246. assert similar_items[0][1]["message:message:character-shingles"] == 1.0
  247. assert similar_items[1][0] == destination.id
  248. assert similar_items[1][1]["message:message:character-shingles"] < 1.0
  249. with self.tasks():
  250. unmerge.delay(
  251. project.id, source.id, destination.id, [list(events.keys())[0]], None, batch_size=5
  252. )
  253. assert (
  254. list(
  255. Group.objects.filter(id=merge_source.id).values_list(
  256. "times_seen", "first_seen", "last_seen"
  257. )
  258. )
  259. == []
  260. )
  261. assert list(
  262. Group.objects.filter(id=source.id).values_list("times_seen", "first_seen", "last_seen")
  263. ) == [(6, time_from_now(10), time_from_now(15))]
  264. assert list(
  265. Group.objects.filter(id=destination.id).values_list(
  266. "times_seen", "first_seen", "last_seen"
  267. )
  268. ) == [(11, time_from_now(0), time_from_now(16))]
  269. assert source.id != destination.id
  270. assert source.project == destination.project
  271. destination_event_ids = set(map(lambda event: event.event_id, list(events.values())[1]))
  272. assert destination_event_ids == set(
  273. UserReport.objects.filter(group_id=source.id).values_list("event_id", flat=True)
  274. )
  275. assert list(
  276. GroupHash.objects.filter(group_id=source.id).values_list("hash", flat=True)
  277. ) == [list(events.keys())[1]]
  278. assert set(
  279. GroupRelease.objects.filter(group_id=source.id).values_list(
  280. "environment", "first_seen", "last_seen"
  281. )
  282. ) == {("production", time_from_now(10), time_from_now(15))}
  283. assert {
  284. (gtv.value, gtv.times_seen)
  285. for gtv in tagstore.get_group_tag_values(
  286. destination,
  287. production_environment.id,
  288. "color",
  289. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  290. )
  291. } == {("red", 4), ("green", 3), ("blue", 3)}
  292. destination_event_ids = set(
  293. map(lambda event: event.event_id, list(events.values())[0] + list(events.values())[2])
  294. )
  295. assert destination_event_ids == set(
  296. UserReport.objects.filter(group_id=destination.id).values_list("event_id", flat=True)
  297. )
  298. assert set(
  299. GroupHash.objects.filter(group_id=destination.id).values_list("hash", flat=True)
  300. ) == {list(events.keys())[0], list(events.keys())[2]}
  301. assert set(
  302. GroupRelease.objects.filter(group_id=destination.id).values_list(
  303. "environment", "first_seen", "last_seen"
  304. )
  305. ) == {
  306. ("production", time_from_now(0), time_from_now(9)),
  307. ("staging", time_from_now(16), time_from_now(16)),
  308. }
  309. assert {
  310. (gtk.value, gtk.times_seen)
  311. for gtk in tagstore.get_group_tag_values(
  312. destination,
  313. production_environment.id,
  314. "color",
  315. tenant_ids={"referrer": "get_tag_values", "organization_id": 1},
  316. )
  317. } == {("red", 4), ("blue", 3), ("green", 3)}
  318. rollup_duration = 3600
  319. time_series = tsdb.get_range(
  320. TSDBModel.group,
  321. [source.id, destination.id],
  322. now - timedelta(seconds=rollup_duration),
  323. time_from_now(17),
  324. rollup_duration,
  325. tenant_ids={"referrer": "get_range", "organization_id": 1},
  326. )
  327. environment_time_series = tsdb.get_range(
  328. TSDBModel.group,
  329. [source.id, destination.id],
  330. now - timedelta(seconds=rollup_duration),
  331. time_from_now(17),
  332. rollup_duration,
  333. environment_ids=[production_environment.id],
  334. tenant_ids={"referrer": "get_range", "organization_id": 1},
  335. )
  336. def get_expected_series_values(rollup, events, function=None):
  337. if function is None:
  338. def function(aggregate, event):
  339. return (aggregate if aggregate is not None else 0) + 1
  340. expected = {}
  341. for event in events:
  342. k = float((to_timestamp(event.datetime) // rollup_duration) * rollup_duration)
  343. expected[k] = function(expected.get(k), event)
  344. return expected
  345. def assert_series_contains(expected, actual, default=0):
  346. actual = dict(actual)
  347. for key, value in expected.items():
  348. assert actual.get(key, 0) == value
  349. for key in set(actual.keys()) - set(expected.keys()):
  350. assert actual.get(key, 0) == default
  351. assert_series_contains(
  352. get_expected_series_values(rollup_duration, list(events.values())[1]),
  353. time_series[source.id],
  354. 0,
  355. )
  356. assert_series_contains(
  357. get_expected_series_values(
  358. rollup_duration, list(events.values())[0] + list(events.values())[2]
  359. ),
  360. time_series[destination.id],
  361. 0,
  362. )
  363. assert_series_contains(
  364. get_expected_series_values(rollup_duration, list(events.values())[1]),
  365. environment_time_series[source.id],
  366. 0,
  367. )
  368. assert_series_contains(
  369. get_expected_series_values(
  370. rollup_duration, list(events.values())[0][:-1] + list(events.values())[2]
  371. ),
  372. environment_time_series[destination.id],
  373. 0,
  374. )
  375. time_series = tsdb.get_distinct_counts_series(
  376. TSDBModel.users_affected_by_group,
  377. [source.id, destination.id],
  378. now - timedelta(seconds=rollup_duration),
  379. time_from_now(17),
  380. rollup_duration,
  381. tenant_ids={"referrer": "r", "organization_id": 1234},
  382. )
  383. environment_time_series = tsdb.get_distinct_counts_series(
  384. TSDBModel.users_affected_by_group,
  385. [source.id, destination.id],
  386. now - timedelta(seconds=rollup_duration),
  387. time_from_now(17),
  388. rollup_duration,
  389. environment_id=production_environment.id,
  390. tenant_ids={"referrer": "r", "organization_id": 1234},
  391. )
  392. def collect_by_user_tag(aggregate, event):
  393. aggregate = aggregate if aggregate is not None else set()
  394. aggregate.add(get_event_user_from_interface(event.data["user"]).tag_value)
  395. return aggregate
  396. for series in [time_series, environment_time_series]:
  397. assert_series_contains(
  398. {
  399. timestamp: len(values)
  400. for timestamp, values in get_expected_series_values(
  401. rollup_duration, list(events.values())[1], collect_by_user_tag
  402. ).items()
  403. },
  404. series[source.id],
  405. )
  406. assert_series_contains(
  407. {
  408. timestamp: len(values)
  409. for timestamp, values in get_expected_series_values(
  410. rollup_duration,
  411. list(events.values())[0] + list(events.values())[2],
  412. collect_by_user_tag,
  413. ).items()
  414. },
  415. time_series[destination.id],
  416. )
  417. def strip_zeroes(data):
  418. for group_id, series in data.items():
  419. for _, values in series:
  420. for key, val in list(values.items()):
  421. if val == 0:
  422. values.pop(key)
  423. return data
  424. def collect_by_release(group, aggregate, event):
  425. aggregate = aggregate if aggregate is not None else {}
  426. release = event.get_tag("sentry:release")
  427. if not release:
  428. return aggregate
  429. release = GroupRelease.objects.get(
  430. group_id=group.id,
  431. environment=event.data["environment"],
  432. release_id=Release.objects.get(
  433. organization_id=project.organization_id, version=release
  434. ).id,
  435. ).id
  436. aggregate[release] = aggregate.get(release, 0) + 1
  437. return aggregate
  438. items = {}
  439. for i in [source.id, destination.id]:
  440. items[i] = list(GroupRelease.objects.filter(group_id=i).values_list("id", flat=True))
  441. time_series = strip_zeroes(
  442. tsdb.get_frequency_series(
  443. TSDBModel.frequent_releases_by_group,
  444. items,
  445. now - timedelta(seconds=rollup_duration),
  446. time_from_now(17),
  447. rollup_duration,
  448. tenant_ids={"referrer": "r", "organization_id": 1234},
  449. )
  450. )
  451. assert_series_contains(
  452. get_expected_series_values(
  453. rollup_duration,
  454. list(events.values())[1],
  455. functools.partial(collect_by_release, source),
  456. ),
  457. time_series[source.id],
  458. {},
  459. )
  460. assert_series_contains(
  461. get_expected_series_values(
  462. rollup_duration,
  463. list(events.values())[0] + list(events.values())[2],
  464. functools.partial(collect_by_release, destination),
  465. ),
  466. time_series[destination.id],
  467. {},
  468. )
  469. items = {}
  470. for i in [source.id, destination.id]:
  471. items[i] = list(Environment.objects.all().values_list("id", flat=True))
  472. time_series = strip_zeroes(
  473. tsdb.get_frequency_series(
  474. TSDBModel.frequent_environments_by_group,
  475. items,
  476. now - timedelta(seconds=rollup_duration),
  477. time_from_now(17),
  478. rollup_duration,
  479. tenant_ids={"referrer": "r", "organization_id": 1234},
  480. )
  481. )
  482. def collect_by_environment(aggregate, event):
  483. aggregate = aggregate if aggregate is not None else {}
  484. environment = Environment.objects.get(
  485. organization_id=project.organization_id, name=event.data["environment"]
  486. ).id
  487. aggregate[environment] = aggregate.get(environment, 0) + 1
  488. return aggregate
  489. assert_series_contains(
  490. get_expected_series_values(
  491. rollup_duration, list(events.values())[1], collect_by_environment
  492. ),
  493. time_series[source.id],
  494. {},
  495. )
  496. assert_series_contains(
  497. get_expected_series_values(
  498. rollup_duration,
  499. list(events.values())[0] + list(events.values())[2],
  500. collect_by_environment,
  501. ),
  502. time_series[destination.id],
  503. {},
  504. )
  505. source_similar_items = features.compare(source)
  506. assert source_similar_items[0] == (
  507. source.id,
  508. {
  509. "exception:message:character-shingles": None,
  510. "exception:stacktrace:application-chunks": None,
  511. "exception:stacktrace:pairs": None,
  512. "message:message:character-shingles": 1.0,
  513. },
  514. )
  515. assert source_similar_items[1][0] == destination.id
  516. assert source_similar_items[1][1]["message:message:character-shingles"] < 1.0
  517. destination_similar_items = features.compare(destination)
  518. assert destination_similar_items[0] == (
  519. destination.id,
  520. {
  521. "exception:message:character-shingles": None,
  522. "exception:stacktrace:application-chunks": None,
  523. "exception:stacktrace:pairs": None,
  524. "message:message:character-shingles": 1.0,
  525. },
  526. )
  527. assert destination_similar_items[1][0] == source.id
  528. assert destination_similar_items[1][1]["message:message:character-shingles"] < 1.0