| 1 | //! Candidate clustering, MMR representative selection, and cross-source entity merging. |
| 2 | //! |
| 3 | //! Mirrors `skills/last30days/scripts/lib/cluster.py`. |
| 4 | |
| 5 | use std::collections::{BTreeMap, BTreeSet}; |
| 6 | |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | |
| 9 | use crate::dedupe::PreparedText; |
| 10 | use crate::entity; |
| 11 | |
| 12 | /// Whether a candidate falls within or outside the requested research date window. |
| 13 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] |
| 14 | #[serde(rename_all = "snake_case")] |
| 15 | #[non_exhaustive] |
| 16 | pub enum WindowState { |
| 17 | /// Candidate is inside the requested window (or undated). |
| 18 | #[default] |
| 19 | InWindow, |
| 20 | /// All dated source items for this candidate fall outside the requested window. |
| 21 | OutOfWindow, |
| 22 | } |
| 23 | |
| 24 | /// Minimal candidate projection passed into [`cluster_candidates`]. |
| 25 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 26 | pub struct ClusterCandidate { |
| 27 | /// Stable candidate identifier. |
| 28 | pub candidate_id: String, |
| 29 | /// Display title. |
| 30 | pub title: String, |
| 31 | /// Display snippet. |
| 32 | pub snippet: String, |
| 33 | /// Distinct sources backing this candidate. |
| 34 | pub sources: Vec<String>, |
| 35 | /// Final reranked score. |
| 36 | pub final_score: f64, |
| 37 | /// Whether this candidate is out of the requested date window. |
| 38 | #[serde(default)] |
| 39 | pub window_state: WindowState, |
| 40 | } |
| 41 | |
| 42 | /// Query plan parameters controlling clustering behavior. |
| 43 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 44 | pub struct ClusterPlan { |
| 45 | /// Plan intent (e.g. `"breaking_news"`, `"opinion"`, `"comparison"`, `"prediction"`, `"how_to"`). |
| 46 | pub intent: String, |
| 47 | /// Cluster mode (`"none"`, `"story"`, etc.). |
| 48 | pub cluster_mode: String, |
| 49 | /// Raw user topic for filtering topic-only entities during cross-source merge. |
| 50 | pub raw_topic: String, |
| 51 | } |
| 52 | |
| 53 | /// Output cluster matching `schema.Cluster`. |
| 54 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] |
| 55 | pub struct ClusterOutput { |
| 56 | /// Cluster identifier (e.g. `"cluster-1"`). |
| 57 | pub cluster_id: String, |
| 58 | /// Representative cluster title. |
| 59 | pub title: String, |
| 60 | /// Ordered candidate identifiers belonging to this cluster. |
| 61 | pub candidate_ids: Vec<String>, |
| 62 | /// Selected MMR representative candidate identifiers (up to 3). |
| 63 | pub representative_ids: Vec<String>, |
| 64 | /// Sorted unique source names represented in this cluster. |
| 65 | pub sources: Vec<String>, |
| 66 | /// Cluster score (highest in-window member score, or highest overall when all are stale). |
| 67 | pub score: f64, |
| 68 | /// Uncertainty tag (`"single-source"`, `"thin-evidence"`, or `None`). |
| 69 | pub uncertainty: Option<String>, |
| 70 | } |
| 71 | |
| 72 | const MMR_LIMIT: usize = 3; |
| 73 | const MMR_DIVERSITY_LAMBDA: f64 = 0.75; |
| 74 | const MIN_SHARED_ENTITIES: usize = 2; |
| 75 | const MAX_CLUSTER_SIZE: usize = 3; |
| 76 | const ENTITY_OVERLAP_THRESHOLD: f64 = 0.45; |
| 77 | const THIN_EVIDENCE_SCORE_FLOOR: f64 = 55.0; |
| 78 | |
| 79 | fn is_clusterable_intent(intent: &str) -> bool { |
| 80 | matches!( |
| 81 | intent, |
| 82 | "breaking_news" | "opinion" | "comparison" | "prediction" |
| 83 | ) |
| 84 | } |
| 85 | |
| 86 | fn candidate_text(candidate: &ClusterCandidate) -> String { |
| 87 | match (candidate.title.is_empty(), candidate.snippet.is_empty()) { |
| 88 | (true, true) => String::new(), |
| 89 | (false, true) => candidate.title.trim().to_owned(), |
| 90 | (true, false) => candidate.snippet.trim().to_owned(), |
| 91 | (false, false) => format!("{} {}", candidate.title, candidate.snippet) |
| 92 | .trim() |
| 93 | .to_owned(), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | fn window_rank(state: WindowState) -> u8 { |
| 98 | match state { |
| 99 | WindowState::InWindow => 0, |
| 100 | WindowState::OutOfWindow => 1, |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | fn compare_cluster_member(a: &ClusterCandidate, b: &ClusterCandidate) -> std::cmp::Ordering { |
| 105 | window_rank(a.window_state) |
| 106 | .cmp(&window_rank(b.window_state)) |
| 107 | .then_with(|| b.final_score.total_cmp(&a.final_score)) |
| 108 | } |
| 109 | |
| 110 | fn cluster_score(group: &[usize], candidates: &[ClusterCandidate]) -> f64 { |
| 111 | if group.is_empty() { |
| 112 | return 0.0; |
| 113 | } |
| 114 | let mut best_in_window: Option<f64> = None; |
| 115 | let mut best_all = f64::NEG_INFINITY; |
| 116 | for &idx in group { |
| 117 | let c = &candidates[idx]; |
| 118 | if c.final_score > best_all { |
| 119 | best_all = c.final_score; |
| 120 | } |
| 121 | if c.window_state == WindowState::InWindow { |
| 122 | best_in_window = Some(match best_in_window { |
| 123 | Some(prev) => prev.max(c.final_score), |
| 124 | None => c.final_score, |
| 125 | }); |
| 126 | } |
| 127 | } |
| 128 | best_in_window.unwrap_or(best_all) |
| 129 | } |
| 130 | |
| 131 | fn cluster_uncertainty(group: &[usize], candidates: &[ClusterCandidate]) -> Option<String> { |
| 132 | if group.is_empty() { |
| 133 | return Some("thin-evidence".to_owned()); |
| 134 | } |
| 135 | let mut sources = BTreeSet::new(); |
| 136 | for &idx in group { |
| 137 | for s in &candidates[idx].sources { |
| 138 | sources.insert(s.as_str()); |
| 139 | } |
| 140 | } |
| 141 | if sources.len() == 1 { |
| 142 | return Some("single-source".to_owned()); |
| 143 | } |
| 144 | if cluster_score(group, candidates) < THIN_EVIDENCE_SCORE_FLOOR { |
| 145 | return Some("thin-evidence".to_owned()); |
| 146 | } |
| 147 | None |
| 148 | } |
| 149 | |
| 150 | fn sorted_sources(group: &[usize], candidates: &[ClusterCandidate]) -> Vec<String> { |
| 151 | let mut set = BTreeSet::new(); |
| 152 | for &idx in group { |
| 153 | for s in &candidates[idx].sources { |
| 154 | set.insert(s.clone()); |
| 155 | } |
| 156 | } |
| 157 | set.into_iter().collect() |
| 158 | } |
| 159 | |
| 160 | fn mmr_representatives( |
| 161 | group: &[usize], |
| 162 | candidates: &[ClusterCandidate], |
| 163 | prepared: &[PreparedText], |
| 164 | ) -> Vec<String> { |
| 165 | let mut remaining: Vec<usize> = group.to_vec(); |
| 166 | let mut selected: Vec<usize> = Vec::with_capacity(MMR_LIMIT.min(group.len())); |
| 167 | |
| 168 | while !remaining.is_empty() && selected.len() < MMR_LIMIT { |
| 169 | if selected.is_empty() { |
| 170 | // Python min(remaining, key=_cluster_sort_key): first minimum wins on ties. |
| 171 | let mut best_pos = 0; |
| 172 | for pos in 1..remaining.len() { |
| 173 | if compare_cluster_member( |
| 174 | &candidates[remaining[pos]], |
| 175 | &candidates[remaining[best_pos]], |
| 176 | ) == std::cmp::Ordering::Less |
| 177 | { |
| 178 | best_pos = pos; |
| 179 | } |
| 180 | } |
| 181 | let best_idx = remaining.remove(best_pos); |
| 182 | selected.push(best_idx); |
| 183 | continue; |
| 184 | } |
| 185 | |
| 186 | // Python max(remaining, key=score): first maximum wins on ties. |
| 187 | let mut best_pos = 0; |
| 188 | let mut best_key: Option<(u8, f64)> = None; |
| 189 | for (pos, &cand_idx) in remaining.iter().enumerate() { |
| 190 | let prep = &prepared[cand_idx]; |
| 191 | let mut diversity_penalty = 0.0_f64; |
| 192 | for &sel_idx in &selected { |
| 193 | let sim = prep.similarity(&prepared[sel_idx]); |
| 194 | if sim > diversity_penalty { |
| 195 | diversity_penalty = sim; |
| 196 | } |
| 197 | } |
| 198 | let base_score = (MMR_DIVERSITY_LAMBDA * candidates[cand_idx].final_score) |
| 199 | - ((1.0 - MMR_DIVERSITY_LAMBDA) * diversity_penalty * 100.0); |
| 200 | let in_window_flag: u8 = |
| 201 | u8::from(candidates[cand_idx].window_state == WindowState::InWindow); |
| 202 | let key = (in_window_flag, base_score); |
| 203 | let is_better = match best_key { |
| 204 | None => true, |
| 205 | Some((prev_flag, prev_score)) => { |
| 206 | key.0 > prev_flag || (key.0 == prev_flag && key.1 > prev_score) |
| 207 | } |
| 208 | }; |
| 209 | if is_better { |
| 210 | best_key = Some(key); |
| 211 | best_pos = pos; |
| 212 | } |
| 213 | } |
| 214 | let best_idx = remaining.remove(best_pos); |
| 215 | selected.push(best_idx); |
| 216 | } |
| 217 | |
| 218 | selected |
| 219 | .into_iter() |
| 220 | .map(|idx| candidates[idx].candidate_id.clone()) |
| 221 | .collect() |
| 222 | } |
| 223 | |
| 224 | struct InternalCluster { |
| 225 | cluster_id: String, |
| 226 | member_indices: Vec<usize>, |
| 227 | output: ClusterOutput, |
| 228 | } |
| 229 | |
| 230 | /// Clusters ranked candidates using greedy leader assignment, MMR representative |
| 231 | /// selection, and cross-source entity merging. |
| 232 | pub fn cluster_candidates( |
| 233 | candidates: &[ClusterCandidate], |
| 234 | plan: &ClusterPlan, |
| 235 | ) -> Vec<ClusterOutput> { |
| 236 | if !is_clusterable_intent(&plan.intent) || plan.cluster_mode == "none" { |
| 237 | return candidates |
| 238 | .iter() |
| 239 | .enumerate() |
| 240 | .map(|(i, c)| { |
| 241 | let mut sources: Vec<String> = c |
| 242 | .sources |
| 243 | .iter() |
| 244 | .cloned() |
| 245 | .collect::<BTreeSet<_>>() |
| 246 | .into_iter() |
| 247 | .collect(); |
| 248 | sources.sort(); |
| 249 | ClusterOutput { |
| 250 | cluster_id: format!("cluster-{}", i + 1), |
| 251 | title: c.title.clone(), |
| 252 | candidate_ids: vec![c.candidate_id.clone()], |
| 253 | representative_ids: vec![c.candidate_id.clone()], |
| 254 | sources, |
| 255 | score: c.final_score, |
| 256 | uncertainty: None, |
| 257 | } |
| 258 | }) |
| 259 | .collect(); |
| 260 | } |
| 261 | |
| 262 | let texts: Vec<String> = candidates.iter().map(candidate_text).collect(); |
| 263 | let prepared: Vec<PreparedText> = texts.iter().map(|t| PreparedText::new(t)).collect(); |
| 264 | |
| 265 | let threshold = if plan.intent == "breaking_news" { |
| 266 | 0.42 |
| 267 | } else { |
| 268 | 0.48 |
| 269 | }; |
| 270 | |
| 271 | let mut groups: Vec<Vec<usize>> = Vec::new(); |
| 272 | for cand_idx in 0..candidates.len() { |
| 273 | let mut assigned = false; |
| 274 | for group in &mut groups { |
| 275 | let leader_idx = group[0]; |
| 276 | if prepared[cand_idx].similarity_at_least(&prepared[leader_idx], threshold) { |
| 277 | group.push(cand_idx); |
| 278 | assigned = true; |
| 279 | break; |
| 280 | } |
| 281 | } |
| 282 | if !assigned { |
| 283 | groups.push(vec![cand_idx]); |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | let mut clusters: Vec<InternalCluster> = Vec::with_capacity(groups.len()); |
| 288 | for (idx, mut group) in groups.into_iter().enumerate() { |
| 289 | group.sort_by(|&a, &b| compare_cluster_member(&candidates[a], &candidates[b])); |
| 290 | let cluster_id = format!("cluster-{}", idx + 1); |
| 291 | let reps = mmr_representatives(&group, candidates, &prepared); |
| 292 | let sources = sorted_sources(&group, candidates); |
| 293 | let score = cluster_score(&group, candidates); |
| 294 | let uncertainty = cluster_uncertainty(&group, candidates); |
| 295 | let candidate_ids = group |
| 296 | .iter() |
| 297 | .map(|&i| candidates[i].candidate_id.clone()) |
| 298 | .collect(); |
| 299 | let title = candidates[group[0]].title.clone(); |
| 300 | clusters.push(InternalCluster { |
| 301 | cluster_id: cluster_id.clone(), |
| 302 | member_indices: group, |
| 303 | output: ClusterOutput { |
| 304 | cluster_id, |
| 305 | title, |
| 306 | candidate_ids, |
| 307 | representative_ids: reps, |
| 308 | sources, |
| 309 | score, |
| 310 | uncertainty, |
| 311 | }, |
| 312 | }); |
| 313 | } |
| 314 | |
| 315 | let topic_entities = entity::extract_text_entities(&plan.raw_topic); |
| 316 | let merged = merge_entity_clusters(clusters, candidates, &texts, &prepared, &topic_entities); |
| 317 | |
| 318 | let mut outputs: Vec<(u8, f64, ClusterOutput)> = merged |
| 319 | .into_iter() |
| 320 | .map(|cl| { |
| 321 | let all_stale = !cl.member_indices.is_empty() |
| 322 | && cl |
| 323 | .member_indices |
| 324 | .iter() |
| 325 | .all(|&idx| candidates[idx].window_state == WindowState::OutOfWindow); |
| 326 | (u8::from(all_stale), cl.output.score, cl.output) |
| 327 | }) |
| 328 | .collect(); |
| 329 | |
| 330 | outputs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| b.1.total_cmp(&a.1))); |
| 331 | outputs.into_iter().map(|(_, _, out)| out).collect() |
| 332 | } |
| 333 | |
| 334 | fn compute_entity_merge_targets( |
| 335 | clusters: &[InternalCluster], |
| 336 | cluster_entities: &[BTreeSet<String>], |
| 337 | topic_entities: &BTreeSet<String>, |
| 338 | ) -> BTreeMap<usize, usize> { |
| 339 | let mut merged_into: BTreeMap<usize, usize> = BTreeMap::new(); |
| 340 | let mut cluster_sizes: Vec<usize> = clusters.iter().map(|cl| cl.member_indices.len()).collect(); |
| 341 | |
| 342 | for i in 0..clusters.len() { |
| 343 | if merged_into.contains_key(&i) || cluster_sizes[i] >= MAX_CLUSTER_SIZE { |
| 344 | continue; |
| 345 | } |
| 346 | let mut sources_i: BTreeSet<&str> = clusters[i] |
| 347 | .output |
| 348 | .sources |
| 349 | .iter() |
| 350 | .map(String::as_str) |
| 351 | .collect(); |
| 352 | for j in (i + 1)..clusters.len() { |
| 353 | if merged_into.contains_key(&j) |
| 354 | || cluster_sizes[i] + cluster_sizes[j] > MAX_CLUSTER_SIZE |
| 355 | { |
| 356 | continue; |
| 357 | } |
| 358 | let sources_j: BTreeSet<&str> = clusters[j] |
| 359 | .output |
| 360 | .sources |
| 361 | .iter() |
| 362 | .map(String::as_str) |
| 363 | .collect(); |
| 364 | if sources_i == sources_j && sources_i.len() == 1 { |
| 365 | continue; |
| 366 | } |
| 367 | if sources_i.contains("polymarket") != sources_j.contains("polymarket") { |
| 368 | continue; |
| 369 | } |
| 370 | let shared_count = cluster_entities[i] |
| 371 | .intersection(&cluster_entities[j]) |
| 372 | .count(); |
| 373 | if shared_count < MIN_SHARED_ENTITIES { |
| 374 | continue; |
| 375 | } |
| 376 | if !topic_entities.is_empty() { |
| 377 | let has_non_topic_i = cluster_entities[i] |
| 378 | .iter() |
| 379 | .any(|e| !topic_entities.contains(e)); |
| 380 | let has_non_topic_j = cluster_entities[j] |
| 381 | .iter() |
| 382 | .any(|e| !topic_entities.contains(e)); |
| 383 | let has_shared_non_topic = cluster_entities[i] |
| 384 | .intersection(&cluster_entities[j]) |
| 385 | .any(|e| !topic_entities.contains(e)); |
| 386 | if (has_non_topic_i || has_non_topic_j) && !has_shared_non_topic { |
| 387 | continue; |
| 388 | } |
| 389 | } |
| 390 | if entity::entity_overlap(&cluster_entities[i], &cluster_entities[j]) |
| 391 | >= ENTITY_OVERLAP_THRESHOLD |
| 392 | { |
| 393 | merged_into.insert(j, i); |
| 394 | cluster_sizes[i] += cluster_sizes[j]; |
| 395 | sources_i.extend(sources_j); |
| 396 | if cluster_sizes[i] >= MAX_CLUSTER_SIZE { |
| 397 | break; |
| 398 | } |
| 399 | } |
| 400 | } |
| 401 | } |
| 402 | merged_into |
| 403 | } |
| 404 | |
| 405 | fn merge_entity_clusters( |
| 406 | clusters: Vec<InternalCluster>, |
| 407 | candidates: &[ClusterCandidate], |
| 408 | texts: &[String], |
| 409 | prepared: &[PreparedText], |
| 410 | topic_entities: &BTreeSet<String>, |
| 411 | ) -> Vec<InternalCluster> { |
| 412 | if clusters.len() < 2 { |
| 413 | return clusters; |
| 414 | } |
| 415 | |
| 416 | let cluster_entities: Vec<BTreeSet<String>> = clusters |
| 417 | .iter() |
| 418 | .map(|cl| { |
| 419 | let mut set = BTreeSet::new(); |
| 420 | for &idx in &cl.member_indices { |
| 421 | set.extend(entity::extract_text_entities(&texts[idx])); |
| 422 | } |
| 423 | set |
| 424 | }) |
| 425 | .collect(); |
| 426 | |
| 427 | let merged_into = compute_entity_merge_targets(&clusters, &cluster_entities, topic_entities); |
| 428 | if merged_into.is_empty() { |
| 429 | return clusters; |
| 430 | } |
| 431 | |
| 432 | let mut result = Vec::with_capacity(clusters.len() - merged_into.len()); |
| 433 | for i in 0..clusters.len() { |
| 434 | if merged_into.contains_key(&i) { |
| 435 | continue; |
| 436 | } |
| 437 | let mut merge_sources = vec![i]; |
| 438 | for (&src, &target) in &merged_into { |
| 439 | if target == i { |
| 440 | merge_sources.push(src); |
| 441 | } |
| 442 | } |
| 443 | if merge_sources.len() == 1 { |
| 444 | let cl = &clusters[i]; |
| 445 | result.push(InternalCluster { |
| 446 | cluster_id: cl.cluster_id.clone(), |
| 447 | member_indices: cl.member_indices.clone(), |
| 448 | output: cl.output.clone(), |
| 449 | }); |
| 450 | continue; |
| 451 | } |
| 452 | |
| 453 | let mut combined_indices: Vec<usize> = Vec::new(); |
| 454 | let mut combined_sources: BTreeSet<String> = BTreeSet::new(); |
| 455 | for &idx in &merge_sources { |
| 456 | combined_indices.extend_from_slice(&clusters[idx].member_indices); |
| 457 | for s in &clusters[idx].output.sources { |
| 458 | combined_sources.insert(s.clone()); |
| 459 | } |
| 460 | } |
| 461 | combined_indices.sort_by(|&a, &b| compare_cluster_member(&candidates[a], &candidates[b])); |
| 462 | let reps = mmr_representatives(&combined_indices, candidates, prepared); |
| 463 | let score = cluster_score(&combined_indices, candidates); |
| 464 | let uncertainty = cluster_uncertainty(&combined_indices, candidates); |
| 465 | let title = candidates[combined_indices[0]].title.clone(); |
| 466 | let candidate_ids = combined_indices |
| 467 | .iter() |
| 468 | .map(|&idx| candidates[idx].candidate_id.clone()) |
| 469 | .collect(); |
| 470 | let cluster_id = clusters[i].cluster_id.clone(); |
| 471 | |
| 472 | result.push(InternalCluster { |
| 473 | cluster_id: cluster_id.clone(), |
| 474 | member_indices: combined_indices, |
| 475 | output: ClusterOutput { |
| 476 | cluster_id, |
| 477 | title, |
| 478 | candidate_ids, |
| 479 | representative_ids: reps, |
| 480 | sources: combined_sources.into_iter().collect(), |
| 481 | score, |
| 482 | uncertainty, |
| 483 | }, |
| 484 | }); |
| 485 | } |
| 486 | |
| 487 | result |
| 488 | } |
| 489 |