| 1 | """Story-diverse ordering of report.clusters (issue #1449 item 5).""" |
| 2 | |
| 3 | import re |
| 4 | |
| 5 | from lib import cluster, cluster_diversity, planner, render, schema |
| 6 | |
| 7 | |
| 8 | def _plan(labels=("primary",), intent="breaking_news", cluster_mode="story"): |
| 9 | return schema.QueryPlan( |
| 10 | intent=intent, |
| 11 | freshness_mode="strict_recent", |
| 12 | cluster_mode=cluster_mode, |
| 13 | raw_topic="Microsoft", |
| 14 | subqueries=[ |
| 15 | schema.SubQuery( |
| 16 | label=label, |
| 17 | search_query=f"microsoft {label}", |
| 18 | ranking_query=f"What about Microsoft {label}?", |
| 19 | sources=["reddit", "youtube", "hackernews"], |
| 20 | ) |
| 21 | for label in labels |
| 22 | ], |
| 23 | source_weights={"reddit": 1.0, "youtube": 1.0, "hackernews": 1.0}, |
| 24 | ) |
| 25 | |
| 26 | |
| 27 | def _candidate(cid, title, score, labels=("primary",), source="youtube", explanation=""): |
| 28 | item = schema.SourceItem( |
| 29 | item_id=cid, |
| 30 | source=source, |
| 31 | title=title, |
| 32 | body=f"Body {cid}", |
| 33 | url=f"https://example.com/{cid}", |
| 34 | snippet=f"Snippet {cid}", |
| 35 | ) |
| 36 | return schema.Candidate( |
| 37 | candidate_id=cid, |
| 38 | item_id=cid, |
| 39 | source=source, |
| 40 | title=title, |
| 41 | url=item.url, |
| 42 | snippet=item.snippet, |
| 43 | subquery_labels=list(labels), |
| 44 | native_ranks={f"primary:{source}": 1}, |
| 45 | local_relevance=0.8, |
| 46 | freshness=80, |
| 47 | engagement=10, |
| 48 | source_quality=0.7, |
| 49 | rrf_score=0.02, |
| 50 | sources=[source], |
| 51 | source_items=[item], |
| 52 | explanation=explanation, |
| 53 | final_score=score, |
| 54 | ) |
| 55 | |
| 56 | |
| 57 | def _singletons(candidates): |
| 58 | return [ |
| 59 | schema.Cluster( |
| 60 | cluster_id=f"cluster-{index}", |
| 61 | title=c.title, |
| 62 | candidate_ids=[c.candidate_id], |
| 63 | representative_ids=[c.candidate_id], |
| 64 | sources=[c.source], |
| 65 | score=c.final_score, |
| 66 | ) |
| 67 | for index, c in enumerate(candidates, start=1) |
| 68 | ] |
| 69 | |
| 70 | |
| 71 | OUTAGE_TITLES = [ |
| 72 | "Microsoft 365 outage takes down Outlook and Teams", |
| 73 | "Massive Microsoft 365 outage hits Outlook and Teams", |
| 74 | "Microsoft 365 outage: Outlook and Teams down worldwide", |
| 75 | "Outlook and Teams down in Microsoft 365 outage", |
| 76 | "Microsoft 365 outage knocks Outlook and Teams offline", |
| 77 | "Microsoft outage: Outlook and Teams down for millions", |
| 78 | ] |
| 79 | |
| 80 | DISTINCT_TITLES = [ |
| 81 | "Azure revenue grows 40 percent in quarterly earnings", |
| 82 | "Copilot adds agent mode for Excel", |
| 83 | "Xbox handheld leaks ahead of launch", |
| 84 | "Windows 12 insider build ships new taskbar", |
| 85 | "Microsoft buys gaming studio for 2 billion", |
| 86 | "Teams pricing changes in Europe", |
| 87 | "GitHub Universe keynote recap", |
| 88 | "Surface Laptop 8 review roundup", |
| 89 | "Bing search share climbs again", |
| 90 | "Edge browser drops legacy extensions", |
| 91 | ] |
| 92 | |
| 93 | |
| 94 | def _ids(clusters): |
| 95 | return [c.cluster_id for c in clusters] |
| 96 | |
| 97 | |
| 98 | def test_near_identical_outage_clusters_take_at_most_three_of_top_eight(): |
| 99 | outage = [_candidate(f"o{i}", t, 90 - i) for i, t in enumerate(OUTAGE_TITLES)] |
| 100 | other = [_candidate(f"d{i}", t, 40 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 101 | candidates = outage + other |
| 102 | clusters = _singletons(candidates) |
| 103 | |
| 104 | ordered = cluster_diversity.diversify_clusters(clusters, candidates, _plan()) |
| 105 | |
| 106 | head = ordered[:8] |
| 107 | outage_ids = {f"cluster-{i}" for i in range(1, 7)} |
| 108 | assert sum(c.cluster_id in outage_ids for c in head) == 3 |
| 109 | # The strongest outage cluster still leads; nothing is dropped. |
| 110 | assert head[0].cluster_id == "cluster-1" |
| 111 | assert sorted(_ids(ordered)) == sorted(_ids(clusters)) |
| 112 | |
| 113 | |
| 114 | def test_floor_clearing_subquery_cluster_gets_a_head_slot(): |
| 115 | distinct = [_candidate(f"d{i}", t, 90 - i) for i, t in enumerate(DISTINCT_TITLES)] |
| 116 | earnings = _candidate("e1", "Earnings beat estimates on cloud demand", 20, labels=("earnings",)) |
| 117 | candidates = distinct + [earnings] |
| 118 | clusters = _singletons(candidates) |
| 119 | |
| 120 | ordered = cluster_diversity.diversify_clusters( |
| 121 | clusters, candidates, _plan(("primary", "earnings")) |
| 122 | ) |
| 123 | |
| 124 | head_ids = _ids(ordered[:8]) |
| 125 | assert "cluster-11" in head_ids |
| 126 | # It takes the last head slot; the first seven keep score order. |
| 127 | assert head_ids[:7] == [f"cluster-{i}" for i in range(1, 8)] |
| 128 | assert head_ids[7] == "cluster-11" |
| 129 | |
| 130 | |
| 131 | def test_differently_phrased_headlines_on_one_subquery_angle_are_capped(): |
| 132 | # Pairwise title overlap is low, but every headline keeps the event word |
| 133 | # the outage subquery searched for. |
| 134 | titles = [ |
| 135 | "What caused the Microsoft outage affecting millions?", |
| 136 | "Microsoft outage impacts millions, expert explains ripple effects", |
| 137 | "Outage live: global disruption will cost Australia billions", |
| 138 | "Massive M365 outage stretches past 15 hours", |
| 139 | "The great outage of 2026", |
| 140 | "Regulators ask questions after the outage", |
| 141 | ] |
| 142 | outage = [ |
| 143 | _candidate(f"o{i}", t, 90 - i, labels=("primary", "outage", "earnings")) |
| 144 | for i, t in enumerate(titles) |
| 145 | ] |
| 146 | other = [_candidate(f"d{i}", t, 40 - i) for i, t in enumerate(DISTINCT_TITLES[1:7])] |
| 147 | earnings = _candidate("e1", "Earnings beat estimates on cloud demand", 20, labels=("earnings",)) |
| 148 | candidates = outage + other + [earnings] |
| 149 | clusters = _singletons(candidates) |
| 150 | |
| 151 | ordered = cluster_diversity.diversify_clusters( |
| 152 | clusters, candidates, _plan(("primary", "outage", "earnings")) |
| 153 | ) |
| 154 | |
| 155 | head = _ids(ordered[:8]) |
| 156 | assert sum(cid in {f"cluster-{i}" for i in range(1, 7)} for cid in head) == 3 |
| 157 | # Retrieved by the earnings subquery is not enough: the outage clusters |
| 158 | # carry the label too, so only the cluster on the earnings angle counts. |
| 159 | assert head[-1] == "cluster-13" |
| 160 | |
| 161 | |
| 162 | def test_below_floor_subquery_cluster_is_never_promoted(): |
| 163 | distinct = [_candidate(f"d{i}", t, 90 - i) for i, t in enumerate(DISTINCT_TITLES)] |
| 164 | off_topic = _candidate( |
| 165 | "e1", "Earnings beat estimates on cloud demand", 20, |
| 166 | labels=("earnings",), explanation="entity-miss demotion", |
| 167 | ) |
| 168 | candidates = distinct + [off_topic] |
| 169 | clusters = _singletons(candidates) |
| 170 | |
| 171 | ordered = cluster_diversity.diversify_clusters( |
| 172 | clusters, candidates, _plan(("primary", "earnings")) |
| 173 | ) |
| 174 | |
| 175 | assert _ids(ordered) == _ids(clusters) |
| 176 | |
| 177 | |
| 178 | def test_distinct_clusters_with_subqueries_represented_keep_order(): |
| 179 | labels = ["primary"] * 10 |
| 180 | labels[2] = "earnings" |
| 181 | labels[6] = "ai" |
| 182 | candidates = [ |
| 183 | _candidate(f"d{i}", t, 90 - i, labels=(labels[i],)) |
| 184 | for i, t in enumerate(DISTINCT_TITLES) |
| 185 | ] |
| 186 | clusters = _singletons(candidates) |
| 187 | |
| 188 | ordered = cluster_diversity.diversify_clusters( |
| 189 | clusters, candidates, _plan(("primary", "earnings", "ai")) |
| 190 | ) |
| 191 | |
| 192 | assert ordered == clusters |
| 193 | |
| 194 | |
| 195 | def test_unsorted_input_without_duplicates_keeps_order(): |
| 196 | # cluster_mode=none keeps candidate order, which is not always score order. |
| 197 | scores = [50, 80, 30, 70, 60] |
| 198 | candidates = [ |
| 199 | _candidate(f"d{i}", DISTINCT_TITLES[i], s) for i, s in enumerate(scores) |
| 200 | ] |
| 201 | clusters = _singletons(candidates) |
| 202 | |
| 203 | assert cluster_diversity.diversify_clusters(clusters, candidates, _plan()) == clusters |
| 204 | |
| 205 | |
| 206 | def test_concept_plan_singleton_duplicates_still_diversify(): |
| 207 | plan = _plan(intent="concept", cluster_mode="none") |
| 208 | candidates = [_candidate(f"o{i}", t, 90 - i) for i, t in enumerate(OUTAGE_TITLES)] |
| 209 | candidates += [_candidate(f"d{i}", t, 40 - i) for i, t in enumerate(DISTINCT_TITLES[:5])] |
| 210 | clusters = cluster.cluster_candidates(candidates, plan) |
| 211 | assert len(clusters) == len(candidates) # no clustering for concept plans |
| 212 | |
| 213 | ordered = cluster_diversity.diversify_clusters(clusters, candidates, plan) |
| 214 | |
| 215 | outage_ids = {f"cluster-{i}" for i in range(1, 7)} |
| 216 | assert sum(c.cluster_id in outage_ids for c in ordered[:8]) <= 3 |
| 217 | |
| 218 | |
| 219 | def _report(candidates, clusters, plan): |
| 220 | sources = sorted({c.source for c in candidates}) |
| 221 | return schema.Report( |
| 222 | topic="Microsoft", |
| 223 | range_from="2026-10-15", |
| 224 | range_to="2026-11-14", |
| 225 | generated_at="2026-11-14T12:00:00+00:00", |
| 226 | provider_runtime=schema.ProviderRuntime( |
| 227 | reasoning_provider="local", |
| 228 | planner_model="mock-planner", |
| 229 | rerank_model="mock-reranker", |
| 230 | ), |
| 231 | query_plan=plan, |
| 232 | clusters=clusters, |
| 233 | ranked_candidates=candidates, |
| 234 | items_by_source={ |
| 235 | s: [i for c in candidates if c.source == s for i in c.source_items] for s in sources |
| 236 | }, |
| 237 | errors_by_source={}, |
| 238 | source_status={ |
| 239 | s: schema.SourceOutcome(source=s, state="ok", items_returned=1) for s in sources |
| 240 | }, |
| 241 | ) |
| 242 | |
| 243 | |
| 244 | def test_below_floor_cluster_in_head_sinks_and_drill_matches_compact_numbering(): |
| 245 | candidates = [_candidate(f"d{i}", t, 90 - i) for i, t in enumerate(DISTINCT_TITLES)] |
| 246 | candidates[2].explanation = "entity-miss demotion" |
| 247 | candidates[4].final_score = 0.0 |
| 248 | plan = _plan() |
| 249 | clusters = cluster_diversity.diversify_clusters(_singletons(candidates), candidates, plan) |
| 250 | |
| 251 | assert _ids(clusters)[-2:] == ["cluster-3", "cluster-5"] |
| 252 | report = _report(candidates, clusters, plan) |
| 253 | compact = render.render_compact(report) |
| 254 | shown = dict(re.findall(r"^### (\d+)\. (.+?) \(score", compact, re.MULTILINE)) |
| 255 | assert len(shown) == 8 |
| 256 | for number, title in shown.items(): |
| 257 | assert planner.resolve_drill_clusters(report, number)[0].title == title |
| 258 | |
| 259 | |
| 260 | def test_compact_numbering_and_drill_agree_after_story_reorder(): |
| 261 | outage = [_candidate(f"o{i}", t, 90 - i) for i, t in enumerate(OUTAGE_TITLES)] |
| 262 | other = [_candidate(f"d{i}", t, 40 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 263 | candidates = outage + other |
| 264 | plan = _plan() |
| 265 | clusters = cluster_diversity.diversify_clusters(_singletons(candidates), candidates, plan) |
| 266 | report = _report(candidates, clusters, plan) |
| 267 | |
| 268 | compact = render.render_compact(report) |
| 269 | shown = dict(re.findall(r"^### (\d+)\. (.+?) \(score", compact, re.MULTILINE)) |
| 270 | assert sum(title in OUTAGE_TITLES for title in shown.values()) == 3 |
| 271 | for number, title in shown.items(): |
| 272 | assert planner.resolve_drill_clusters(report, number)[0].title == title |
| 273 | |
| 274 | |
| 275 | def test_title_chain_and_angle_share_one_story_cap(): |
| 276 | # The first near-duplicate carries only the primary label; the next three |
| 277 | # carry the outage angle. They are still one story: at most three in the head. |
| 278 | outage = [_candidate("o0", OUTAGE_TITLES[0], 95)] + [ |
| 279 | _candidate(f"o{i}", OUTAGE_TITLES[i], 95 - i, labels=("outage",)) |
| 280 | for i in range(1, 4) |
| 281 | ] |
| 282 | other = [_candidate(f"d{i}", t, 40 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 283 | candidates = outage + other |
| 284 | clusters = _singletons(candidates) |
| 285 | |
| 286 | ordered = cluster_diversity.diversify_clusters( |
| 287 | clusters, candidates, _plan(("primary", "outage")) |
| 288 | ) |
| 289 | |
| 290 | outage_ids = {f"cluster-{i}" for i in range(1, 5)} |
| 291 | assert sum(c.cluster_id in outage_ids for c in ordered[:8]) == 3 |
| 292 | |
| 293 | |
| 294 | def test_primary_title_match_counts_against_the_whole_angle_story(): |
| 295 | # The first cluster joins the story by title, not by its retrieval label. |
| 296 | # The last two are related by the angle, not by wording. |
| 297 | outage = [ |
| 298 | _candidate("o0", "Microsoft 365 outage takes down Outlook", 100), |
| 299 | _candidate("o1", "Microsoft 365 outage takes down Outlook worldwide", 95, labels=("outage",)), |
| 300 | _candidate("o2", "Outage live: disruption costs Australia billions", 35, labels=("outage",)), |
| 301 | _candidate("o3", "Regulators question hospitals after the outage", 34, labels=("outage",)), |
| 302 | ] |
| 303 | other = [_candidate(f"d{i}", t, 20 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 304 | candidates = outage + other |
| 305 | clusters = _singletons(candidates) |
| 306 | plan = _plan(("primary", "outage")) |
| 307 | |
| 308 | ordered = cluster_diversity.diversify_clusters(clusters, candidates, plan) |
| 309 | |
| 310 | assert ordered[:8] == [*clusters[:3], *clusters[4:9]] |
| 311 | assert _ids(ordered[8:]) == ["cluster-4", "cluster-10"] |
| 312 | |
| 313 | |
| 314 | def test_title_matching_two_picked_stories_cannot_overfill_the_combined_story(): |
| 315 | # The roundup is similar to both sets of titles. Accounting only for its |
| 316 | # closest match would let a five-cluster chain into the head. |
| 317 | candidates = [ |
| 318 | _candidate("a0", "Outlook message delivery delays", 100), |
| 319 | _candidate("a1", "Outlook message delivery delays reported", 99), |
| 320 | _candidate("b0", "Azure database connection failures", 90), |
| 321 | _candidate("b1", "Azure database connection failures hit region", 89), |
| 322 | _candidate("both", "Outlook message delivery delays and Azure database connection failures", 30), |
| 323 | ] + [_candidate(f"d{i}", t, 10 - i) for i, t in enumerate(DISTINCT_TITLES[:5])] |
| 324 | clusters = _singletons(candidates) |
| 325 | |
| 326 | ordered = cluster_diversity.diversify_clusters(clusters, candidates, _plan()) |
| 327 | |
| 328 | assert set(_ids(clusters[:4])) <= set(_ids(ordered[:8])) |
| 329 | assert _ids(ordered[8:]) == ["cluster-5", "cluster-10"] |
| 330 | |
| 331 | |
| 332 | def test_title_bridge_under_cap_unifies_both_selected_stories(): |
| 333 | candidates = [ |
| 334 | _candidate("a", "Outlook message delivery delays", 100), |
| 335 | _candidate("b", "Azure database connection failures", 90), |
| 336 | _candidate("both", "Outlook message delivery delays and Azure database connection failures", 80), |
| 337 | _candidate("b2", "Azure database connection failures again", 50), |
| 338 | ] + [_candidate(f"d{i}", t, 20 - i) for i, t in enumerate(DISTINCT_TITLES[:5])] |
| 339 | clusters = _singletons(candidates) |
| 340 | |
| 341 | ordered = cluster_diversity.diversify_clusters(clusters, candidates, _plan()) |
| 342 | |
| 343 | assert ordered == [*clusters[:3], *clusters[4:], clusters[3]] |
| 344 | |
| 345 | |
| 346 | def test_out_of_window_subquery_cluster_is_not_reserved_a_head_slot(): |
| 347 | distinct = [_candidate(f"d{i}", t, 90 - i) for i, t in enumerate(DISTINCT_TITLES)] |
| 348 | earnings = _candidate("e1", "Earnings beat estimates on cloud demand", 20, labels=("earnings",)) |
| 349 | earnings.source_items[0].published_at = "2025-01-10" |
| 350 | earnings.metadata["range_from"] = "2026-10-16" |
| 351 | earnings.metadata["range_to"] = "2026-11-15" |
| 352 | assert schema.candidate_out_of_window(earnings) |
| 353 | candidates = distinct + [earnings] |
| 354 | clusters = _singletons(candidates) |
| 355 | |
| 356 | ordered = cluster_diversity.diversify_clusters( |
| 357 | clusters, candidates, _plan(("primary", "earnings")) |
| 358 | ) |
| 359 | |
| 360 | assert _ids(ordered[:8]) == [f"cluster-{i}" for i in range(1, 9)] |
| 361 | |
| 362 | |
| 363 | def test_out_of_window_cluster_is_not_promoted_past_current_ones(): |
| 364 | # A near-duplicate's penalty makes the next non-duplicate the default; an |
| 365 | # old cluster must not take that place ahead of current stories. |
| 366 | outage = [_candidate(f"o{i}", OUTAGE_TITLES[i], 95 - i) for i in range(2)] |
| 367 | old = _candidate("old", "Earnings beat estimates on cloud demand", 93) |
| 368 | old.source_items[0].published_at = "2025-01-10" |
| 369 | old.metadata["range_from"] = "2026-10-16" |
| 370 | old.metadata["range_to"] = "2026-11-15" |
| 371 | assert schema.candidate_out_of_window(old) |
| 372 | current = [_candidate(f"d{i}", t, 60 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 373 | candidates = outage + [old] + current |
| 374 | clusters = _singletons(candidates) |
| 375 | |
| 376 | ordered = _ids(cluster_diversity.diversify_clusters(clusters, candidates, _plan(("primary",)))) |
| 377 | |
| 378 | # The old cluster keeps its incoming place, after the current near-duplicate. |
| 379 | assert ordered[:3] == ["cluster-1", "cluster-2", "cluster-3"] |
| 380 | |
| 381 | |
| 382 | def test_out_of_window_cluster_does_not_take_a_capped_storys_slot(): |
| 383 | # Four outage near-duplicates: the fourth is story-capped. The old cluster |
| 384 | # behind it must not take its slot ahead of the current cluster after it. |
| 385 | outage = [_candidate(f"o{i}", OUTAGE_TITLES[i], 95 - i) for i in range(4)] |
| 386 | # Current clusters score low enough that the penalized near-duplicates |
| 387 | # still win, so the outage story reaches its cap inside the head. |
| 388 | old = _candidate("old", "Earnings beat estimates on cloud demand", 90) |
| 389 | old.source_items[0].published_at = "2025-01-10" |
| 390 | old.metadata["range_from"] = "2026-10-16" |
| 391 | old.metadata["range_to"] = "2026-11-15" |
| 392 | current = [_candidate(f"d{i}", t, 20 - i) for i, t in enumerate(DISTINCT_TITLES[:6])] |
| 393 | candidates = outage + [old] + current |
| 394 | clusters = _singletons(candidates) |
| 395 | |
| 396 | ordered = _ids(cluster_diversity.diversify_clusters(clusters, candidates, _plan(("primary",)))) |
| 397 | |
| 398 | assert ordered[:3] == ["cluster-1", "cluster-2", "cluster-3"] |
| 399 | assert ordered[3] == "cluster-6" |
| 400 | assert ordered.index("cluster-5") > ordered.index("cluster-4") |
| 401 |