返回 last30days-skill
cluster_diversity.py
根目录 / skills / last30days / scripts / lib / cluster_diversity.py
1 """Story-diverse ordering of ranked clusters.
2
3 Clustering can split one dominant story into many singleton clusters (the
4 same-source merge ban, leader-only matching, or a ``cluster_mode=none`` plan),
5 and clusters are ranked by score alone. Without a cross-cluster rule the eight
6 clusters the chat report sees can all be the same event while other stories
7 the plan searched for sit at rank 19 and beyond.
8
9 ``diversify_clusters`` reorders ``report.clusters`` once, in the pipeline,
10 right after clustering. It lives there and not in render so that the compact
11 numbering, the saved raw file and ``--drill N`` (which resolves
12 ``report.clusters[N - 1]``) all point at the same cluster.
13
14 Rules, applied to the head window (the first ``HEAD_SIZE`` slots):
15
16 - Near-duplicates are penalized MMR style. Similarity is measured on titles
17 only (the cluster title plus its representatives' titles); snippets are
18 long and inflate overlap.
19 - One story takes at most ``STORY_CAP`` head slots. A story is a chain of
20 title near-duplicates, or a subquery angle: clusters retrieved by a
21 non-primary subquery whose titles use that subquery's own search terms
22 (``outage`` for ``microsoft outage`` on the topic ``Microsoft``). Headlines
23 about one event are often phrased too differently for pairwise similarity,
24 but they keep the event's word. Selected clusters linked by either rule
25 share a single cap.
26 - Each non-primary subquery with a cluster that clears the relevance floor
27 gets at least one head slot.
28
29 Clusters below the relevance floor sink after every solid cluster, so the
30 visible window never wastes a slot on a cluster render will hide. With no
31 near-duplicates and every floor-clearing non-primary subquery already in the
32 head, the solid order is unchanged.
33 """
34
35 from __future__ import annotations
36
37 from collections import Counter
38 from collections.abc import Iterable
39 from typing import NamedTuple
40
41 from . import cjk, dedupe, rerank, schema
42
43 HEAD_SIZE = 8
44 STORY_CAP = 3
45 # Title similarity at or above this marks two clusters as the same story.
46 NEAR_DUPLICATE_SIMILARITY = 0.4
47 # MMR weight: a near-duplicate's score is scaled by (1 - weight * similarity).
48 DUPLICATE_PENALTY = 0.6
49
50
51 def cluster_clears_relevance_floor(
52 cluster: schema.Cluster,
53 candidate_by_id: dict[str, schema.Candidate],
54 ) -> bool:
55 """Mirror of render's relevance floor for one cluster.
56
57 Positive score, and at least one known member passes
58 ``rerank.candidate_relevance_ok``. Missing member records are not treated
59 as misses, matching ``render._clusters_clearing_relevance_floor``.
60 """
61 if cluster.score <= 0:
62 return False
63 members = [
64 candidate_by_id[candidate_id]
65 for candidate_id in cluster.candidate_ids
66 if candidate_id in candidate_by_id
67 ]
68 if members and not any(rerank.candidate_relevance_ok(c) for c in members):
69 return False
70 return True
71
72
73 def _only_out_of_window(
74 cluster: schema.Cluster,
75 candidate_by_id: dict[str, schema.Candidate],
76 ) -> bool:
77 """Every known member of the cluster is out of the requested window."""
78 members = [
79 candidate_by_id[candidate_id]
80 for candidate_id in cluster.candidate_ids
81 if candidate_id in candidate_by_id
82 ]
83 return bool(members) and all(schema.candidate_out_of_window(c) for c in members)
84
85
86 def _terms(text: str, exclude: frozenset[str] = frozenset()) -> frozenset[str]:
87 """Content tokens of ``text``, minus stopwords and ``exclude``."""
88 return frozenset(
89 token
90 for token in cjk.segment(dedupe.normalize_text(text))
91 if len(token) > 1 and token not in dedupe.STOPWORDS and token not in exclude
92 )
93
94
95 def _angle_terms(plan: schema.QueryPlan | None) -> dict[str, frozenset[str]]:
96 """Non-primary subquery label -> its own search terms, in plan order.
97
98 The topic's tokens are removed, so ``microsoft outage`` on the topic
99 ``Microsoft`` leaves ``{outage}``: the angle the planner named.
100 """
101 if plan is None or not plan.subqueries:
102 return {}
103 topic = _terms(plan.raw_topic or "")
104 primary = plan.subqueries[0].label
105 angles: dict[str, frozenset[str]] = {}
106 for subquery in plan.subqueries[1:]:
107 if subquery.label == primary or subquery.label in angles:
108 continue
109 angles[subquery.label] = _terms(subquery.search_query, topic)
110 return angles
111
112
113 def _carried_labels(
114 cluster: schema.Cluster,
115 candidate_by_id: dict[str, schema.Candidate],
116 wanted: Iterable[str],
117 ) -> set[str]:
118 """Subquery labels carried by the cluster's on-topic members."""
119 wanted = set(wanted)
120 labels: set[str] = set()
121 for candidate_id in cluster.candidate_ids:
122 candidate = candidate_by_id.get(candidate_id)
123 if candidate is None or not rerank.candidate_relevance_ok(candidate):
124 continue
125 labels.update(label for label in candidate.subquery_labels if label in wanted)
126 return labels
127
128
129 def _cluster_angle(
130 title_terms: frozenset[str],
131 carried: set[str],
132 angles: dict[str, frozenset[str]],
133 ) -> str | None:
134 """The subquery angle a cluster's titles belong to, if any.
135
136 A cluster belongs to an angle when one of its on-topic members came from
137 that subquery and its titles use that subquery's own search terms. Ties go
138 to the earlier subquery in the plan.
139 """
140 best, best_hits = None, 0
141 for label, terms in angles.items():
142 if label not in carried or not terms:
143 continue
144 hits = len(title_terms & terms)
145 if hits > best_hits:
146 best, best_hits = label, hits
147 return best
148
149
150 def _title_texts(
151 cluster: schema.Cluster,
152 candidate_by_id: dict[str, schema.Candidate],
153 ) -> list[dedupe._PreparedText]:
154 titles: list[str] = []
155 for title in [cluster.title] + [
156 candidate_by_id[cid].title
157 for cid in cluster.representative_ids
158 if cid in candidate_by_id
159 ]:
160 if title and title not in titles:
161 titles.append(title)
162 return [dedupe._PreparedText(title) for title in titles]
163
164
165 def _similarity(
166 left: Iterable[dedupe._PreparedText],
167 right: Iterable[dedupe._PreparedText],
168 ) -> float:
169 right = list(right)
170 return max(
171 (dedupe.prepared_similarity(a, b) for a in left for b in right),
172 default=0.0,
173 )
174
175
176 def diversify_clusters(
177 clusters: list[schema.Cluster],
178 candidates: list[schema.Candidate],
179 plan: schema.QueryPlan | None,
180 *,
181 head_size: int = HEAD_SIZE,
182 story_cap: int = STORY_CAP,
183 ) -> list[schema.Cluster]:
184 """Return ``clusters`` reordered for story and subquery diversity."""
185 if not clusters:
186 return clusters
187 candidate_by_id = {c.candidate_id: c for c in candidates}
188 solid: list[schema.Cluster] = []
189 sunk: list[schema.Cluster] = []
190 for cluster in clusters:
191 if cluster_clears_relevance_floor(cluster, candidate_by_id):
192 solid.append(cluster)
193 else:
194 sunk.append(cluster)
195 if len(solid) <= 1:
196 return solid + sunk
197
198 angles = _angle_terms(plan)
199 texts = [_title_texts(c, candidate_by_id) for c in solid]
200 angle_of: list[str | None] = []
201 covers: list[set[str]] = []
202 stale = [_only_out_of_window(cluster, candidate_by_id) for cluster in solid]
203 for cluster, prepared in zip(solid, texts):
204 carried = _carried_labels(cluster, candidate_by_id, angles)
205 title_terms = frozenset().union(*(p.tokens for p in prepared))
206 angle = _cluster_angle(title_terms, carried, angles)
207 angle_of.append(angle)
208 # A subquery with its own terms is represented only by a cluster on
209 # its angle; one whose search terms are just the topic is represented
210 # by any cluster it retrieved.
211 # A cluster holding only out-of-window evidence never fills a
212 # subquery's reserved slot: it stays behind current clusters.
213 covers.append(
214 set()
215 if stale[len(covers)]
216 else ({angle} if angle else set())
217 | {label for label in carried if not angles[label]}
218 )
219 # Only labels some solid cluster represents can be reserved.
220 uncovered = set().union(*covers)
221
222 remaining = list(range(len(solid)))
223 # Picked cluster indices in head order, each mapped to its current story.
224 story_of: dict[int, int] = {}
225
226 def story_matches(index: int) -> tuple[float, frozenset[int]]:
227 best_sim = 0.0
228 stories: set[int] = set()
229 angle = angle_of[index]
230 for chosen, story in story_of.items():
231 sim = _similarity(texts[index], texts[chosen])
232 best_sim = max(best_sim, sim)
233 if sim >= NEAR_DUPLICATE_SIMILARITY or (
234 angle is not None and angle == angle_of[chosen]
235 ):
236 stories.add(story)
237 return best_sim, frozenset(stories)
238
239 while remaining and len(story_of) < head_size:
240 slots_left = head_size - len(story_of)
241 story_counts = Counter(story_of.values())
242 options: list[_Option] = []
243 for index in remaining:
244 sim, stories = story_matches(index)
245 if 1 + sum(story_counts[story] for story in stories) > story_cap:
246 continue
247 options.append(_Option(index, sim, sim >= NEAR_DUPLICATE_SIMILARITY, stories))
248 if not options:
249 break
250
251 # A label whose clusters are all story-capped cannot be reserved.
252 uncovered &= set().union(*(covers[opt.index] for opt in options))
253 if uncovered and slots_left <= len(uncovered):
254 options = [opt for opt in options if covers[opt.index] & uncovered]
255 # Out-of-window clusters are never promoted: one is eligible only
256 # while no unplaced current cluster comes before it in the incoming
257 # order, including one the story cap just skipped.
258 first_current = min(
259 (index for index in remaining if not stale[index]), default=None,
260 )
261 if first_current is not None:
262 options = [
263 opt for opt in options
264 if not stale[opt.index] or opt.index < first_current
265 ]
266 if not options:
267 break
268
269 choice = _mmr_pick(options, solid)
270 story = min(choice.stories, default=choice.index)
271 for chosen, previous_story in story_of.items():
272 if previous_story in choice.stories:
273 story_of[chosen] = story
274 story_of[choice.index] = story
275 uncovered -= covers[choice.index]
276 remaining.remove(choice.index)
277
278 head = [solid[i] for i in story_of]
279 tail = [solid[i] for i in range(len(solid)) if i not in story_of]
280 return head + tail + sunk
281
282
283 class _Option(NamedTuple):
284 index: int
285 similarity: float
286 duplicate: bool # a title near-duplicate of a picked cluster
287 stories: frozenset[int]
288
289
290 def _mmr_pick(options: list[_Option], solid: list[schema.Cluster]) -> _Option:
291 """Pick the next head cluster, preserving the incoming order when nothing
292 is a near-duplicate.
293
294 The first non-duplicate option (in incoming order) is the default. A
295 near-duplicate ahead of it wins only if its penalized score still beats the
296 default's score. When every option is a near-duplicate, the best penalized
297 score wins, ties by incoming order.
298 """
299 def penalized(opt: _Option) -> float:
300 score = solid[opt.index].score
301 if not opt.duplicate:
302 return score
303 return score * (1.0 - DUPLICATE_PENALTY * opt.similarity)
304
305 default = next((opt for opt in options if not opt.duplicate), None)
306 if default is None:
307 return max(options, key=lambda opt: (penalized(opt), -opt.index))
308 best = default
309 for opt in options:
310 if opt.index >= default.index:
311 break
312 if penalized(opt) >= solid[default.index].score and (
313 best is default or penalized(opt) > penalized(best)
314 ):
315 best = opt
316 return best
317
317 lines PYTHON