anno 0.10.0

NER, coreference resolution, relation extraction, PII detection, and zero-shot entity types
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
//! Cluster encoder for cross-context coreference resolution.
//!
//! This module provides shared primitives for representing within-context clusters and scoring
//! merges across contexts (document windows or separate documents). It is intentionally dependency
//! light so it can be used by both `anno` and `anno-eval` without cycles.

use std::collections::HashMap;

/// A mention within a cluster, represented by character offsets.
#[derive(Debug, Clone)]
pub struct ClusterMention {
    /// Start character offset in the original text.
    pub start: usize,
    /// End character offset (exclusive).
    pub end: usize,
    /// Surface text of the mention.
    pub text: String,
    /// Context ID (document or window index).
    pub context_id: usize,
}

/// A coreference cluster containing mentions from a single context.
#[derive(Debug, Clone)]
pub struct LocalCluster {
    /// Unique identifier within the context.
    pub id: usize,
    /// Mentions in this cluster.
    pub mentions: Vec<ClusterMention>,
    /// Context identifier (document ID or window index).
    pub context_id: usize,
    /// Canonical representative (e.g., first non-pronoun mention).
    pub canonical: Option<String>,
}

impl LocalCluster {
    /// Create a new local cluster.
    #[must_use]
    pub fn new(id: usize, context_id: usize) -> Self {
        Self {
            id,
            mentions: Vec::new(),
            context_id,
            canonical: None,
        }
    }

    /// Add a mention to the cluster.
    pub fn add_mention(&mut self, mention: ClusterMention) {
        self.mentions.push(mention);
    }

    /// Compute canonical form from mentions (heuristic: longest non-pronoun).
    pub fn compute_canonical(&mut self) {
        let pronouns = [
            "he", "she", "it", "they", "him", "her", "them", "his", "hers", "its",
        ];

        let canonical = self
            .mentions
            .iter()
            .filter(|m| !pronouns.contains(&m.text.to_lowercase().as_str()))
            .max_by_key(|m| m.text.len())
            .map(|m| m.text.clone());

        self.canonical = canonical.or_else(|| self.mentions.first().map(|m| m.text.clone()));
    }
}

/// Configuration for cluster encoding.
#[derive(Debug, Clone)]
pub struct ClusterEncoderConfig {
    /// Hidden dimension from base encoder (e.g., 1024 for DeBERTa-large).
    pub hidden_dim: usize,
    /// Number of attention heads in a cluster Transformer.
    pub num_heads: usize,
    /// Pooling strategy for cluster embedding.
    pub pooling: PoolingStrategy,
    /// Dropout rate.
    pub dropout: f32,
}

impl Default for ClusterEncoderConfig {
    fn default() -> Self {
        Self {
            hidden_dim: 1024,
            num_heads: 8,
            pooling: PoolingStrategy::Mean,
            dropout: 0.1,
        }
    }
}

/// Pooling strategy for reducing mention embeddings to a cluster embedding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PoolingStrategy {
    /// Average all mention embeddings.
    Mean,
    /// Use first mention's embedding (assumes canonical ordering).
    First,
    /// Attention-weighted pooling with a learned query.
    AttentionWeighted,
    /// Max pooling per dimension.
    Max,
}

/// Cluster embedding: a fixed-size representation of a coreference cluster.
#[derive(Debug, Clone)]
pub struct ClusterEmbedding {
    /// The embedding vector.
    pub embedding: Vec<f32>,
    /// Source cluster ID.
    pub cluster_id: usize,
    /// Source context ID.
    pub context_id: usize,
    /// Number of mentions in the source cluster.
    pub mention_count: usize,
}

/// Trait for encoding clusters into fixed-size embeddings.
pub trait ClusterEncoder: Send + Sync {
    /// Encode a single cluster into an embedding.
    fn encode_cluster(
        &self,
        cluster: &LocalCluster,
        hidden_states: Option<&[Vec<f32>]>,
    ) -> ClusterEmbedding;

    /// Encode multiple clusters (batch operation).
    fn encode_clusters(
        &self,
        clusters: &[LocalCluster],
        hidden_states: Option<&[Vec<f32>]>,
    ) -> Vec<ClusterEmbedding> {
        clusters
            .iter()
            .map(|c| self.encode_cluster(c, hidden_states))
            .collect()
    }

    /// Expected embedding dimension.
    fn embedding_dim(&self) -> usize;
}

impl std::fmt::Debug for dyn ClusterEncoder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("dyn ClusterEncoder")
            .field("embedding_dim", &self.embedding_dim())
            .finish()
    }
}

/// Simple heuristic cluster encoder using hashed character n-grams.
#[derive(Debug, Clone)]
pub struct HeuristicClusterEncoder {
    dim: usize,
    ngram_size: usize,
}

impl HeuristicClusterEncoder {
    /// Create a new heuristic encoder.
    #[must_use]
    pub fn new(dim: usize) -> Self {
        Self { dim, ngram_size: 3 }
    }

    fn hash_string(&self, s: &str) -> Vec<f32> {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut embedding = vec![0.0f32; self.dim];
        let chars: Vec<char> = s.to_lowercase().chars().collect();

        for window in chars.windows(self.ngram_size) {
            let ngram: String = window.iter().collect();
            let mut hasher = DefaultHasher::new();
            ngram.hash(&mut hasher);
            let idx = (hasher.finish() as usize) % self.dim;
            embedding[idx] += 1.0;
        }

        let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for x in &mut embedding {
                *x /= norm;
            }
        }

        embedding
    }
}

impl ClusterEncoder for HeuristicClusterEncoder {
    fn encode_cluster(
        &self,
        cluster: &LocalCluster,
        _hidden_states: Option<&[Vec<f32>]>,
    ) -> ClusterEmbedding {
        let mut combined = vec![0.0f32; self.dim];

        for mention in &cluster.mentions {
            let mention_emb = self.hash_string(&mention.text);
            for (i, v) in mention_emb.into_iter().enumerate() {
                combined[i] += v;
            }
        }

        let norm: f32 = combined.iter().map(|x| x * x).sum::<f32>().sqrt();
        if norm > 0.0 {
            for x in &mut combined {
                *x /= norm;
            }
        }

        ClusterEmbedding {
            embedding: combined,
            cluster_id: cluster.id,
            context_id: cluster.context_id,
            mention_count: cluster.mentions.len(),
        }
    }

    fn embedding_dim(&self) -> usize {
        self.dim
    }
}

/// Configuration for merge scoring.
#[derive(Debug, Clone)]
pub struct MergeScorerConfig {
    /// Input embedding dimension.
    pub embedding_dim: usize,
    /// Hidden dimension in scorer MLP.
    pub hidden_dim: usize,
    /// Threshold for merge decision.
    pub threshold: f32,
}

impl Default for MergeScorerConfig {
    fn default() -> Self {
        Self {
            embedding_dim: 256,
            hidden_dim: 128,
            threshold: 0.5,
        }
    }
}

/// Trait for scoring cluster merge probability.
pub trait MergeScorer: Send + Sync {
    /// Score the probability that two clusters should be merged.
    ///
    /// Returns a value clamped to \([0, 1]\).
    fn score(&self, cluster_a: &ClusterEmbedding, cluster_b: &ClusterEmbedding) -> f32;

    /// Batch scoring for efficiency.
    fn score_batch(
        &self,
        clusters_a: &[ClusterEmbedding],
        clusters_b: &[ClusterEmbedding],
    ) -> Vec<Vec<f32>> {
        clusters_a
            .iter()
            .map(|a| clusters_b.iter().map(|b| self.score(a, b)).collect())
            .collect()
    }

    /// Get merge decisions above threshold.
    fn get_merges(
        &self,
        clusters_a: &[ClusterEmbedding],
        clusters_b: &[ClusterEmbedding],
        threshold: f32,
    ) -> Vec<(usize, usize, f32)> {
        let scores = self.score_batch(clusters_a, clusters_b);
        let mut merges = Vec::new();

        for (i, row) in scores.iter().enumerate() {
            for (j, &score) in row.iter().enumerate() {
                if score >= threshold {
                    merges.push((i, j, score));
                }
            }
        }

        merges.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));
        merges
    }
}

/// Simple cosine similarity scorer (CPU fallback).
///
/// Returns raw cosine similarity in `[0, 1]`. Thresholding is handled
/// externally (via [`MergeScorer::get_merges`] or call-site comparison).
#[derive(Debug, Clone, Default)]
pub struct CosineMergeScorer;

impl CosineMergeScorer {
    /// Create a new cosine similarity scorer.
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl MergeScorer for CosineMergeScorer {
    fn score(&self, cluster_a: &ClusterEmbedding, cluster_b: &ClusterEmbedding) -> f32 {
        let a = &cluster_a.embedding;
        let b = &cluster_b.embedding;

        if a.len() != b.len() {
            return 0.0;
        }

        let dot: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
        let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
        let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();

        if norm_a > 0.0 && norm_b > 0.0 {
            (dot / (norm_a * norm_b)).clamp(0.0, 1.0)
        } else {
            0.0
        }
    }
}

/// Configuration for cross-context resolution.
#[derive(Debug, Clone)]
pub struct CrossContextConfig {
    /// Merge threshold.
    pub threshold: f32,
    /// Whether to compare clusters from the same context.
    pub compare_same_context: bool,
    /// Maximum clusters to consider (for efficiency).
    pub max_clusters: Option<usize>,
}

impl Default for CrossContextConfig {
    fn default() -> Self {
        Self {
            threshold: 0.5,
            compare_same_context: false,
            max_clusters: None,
        }
    }
}

/// A merged cross-context cluster.
#[derive(Debug, Clone)]
pub struct MergedCluster {
    /// Unique ID for the merged cluster.
    pub id: usize,
    /// Source local clusters (context_id, cluster_id).
    pub source_clusters: Vec<(usize, usize)>,
    /// All mentions from merged clusters.
    pub mentions: Vec<ClusterMention>,
    /// Canonical representative.
    pub canonical: Option<String>,
}

/// Cross-context coreference resolution combining encoder and scorer.
pub struct CrossContextResolver<E: ClusterEncoder, S: MergeScorer> {
    encoder: E,
    scorer: S,
    config: CrossContextConfig,
}

impl<E: ClusterEncoder, S: MergeScorer> CrossContextResolver<E, S> {
    /// Create a new cross-context resolver.
    #[must_use]
    pub fn new(encoder: E, scorer: S, config: CrossContextConfig) -> Self {
        Self {
            encoder,
            scorer,
            config,
        }
    }

    /// Resolve coreference across multiple contexts.
    #[must_use]
    pub fn resolve(
        &self,
        local_clusters: &HashMap<usize, Vec<LocalCluster>>,
        hidden_states: Option<&HashMap<usize, Vec<Vec<f32>>>>,
    ) -> Vec<MergedCluster> {
        // 1) Encode all clusters.
        let mut all_embeddings: Vec<ClusterEmbedding> = Vec::new();
        for (context_id, clusters) in local_clusters {
            let hs = hidden_states.and_then(|h| h.get(context_id).map(|v| v.as_slice()));
            let embeddings = self.encoder.encode_clusters(clusters, hs);
            all_embeddings.extend(embeddings);
        }

        // Optional: cap number of clusters for very large inputs.
        if let Some(max) = self.config.max_clusters {
            if all_embeddings.len() > max {
                all_embeddings.truncate(max);
            }
        }

        // 2) Score pairwise merges.
        let mut merge_decisions: Vec<(usize, usize, f32)> = Vec::new();
        for (i, emb_a) in all_embeddings.iter().enumerate() {
            for (j, emb_b) in all_embeddings.iter().enumerate().skip(i + 1) {
                if !self.config.compare_same_context && emb_a.context_id == emb_b.context_id {
                    continue;
                }
                let score = self.scorer.score(emb_a, emb_b);
                if score >= self.config.threshold {
                    merge_decisions.push((i, j, score));
                }
            }
        }
        merge_decisions.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));

        // 3) Union-find.
        let mut uf = UnionFind::new(all_embeddings.len());
        for (i, j, _score) in merge_decisions {
            uf.union(i, j);
        }

        // 4) Group by root.
        let mut merged_map: HashMap<usize, Vec<usize>> = HashMap::new();
        for i in 0..all_embeddings.len() {
            let root = uf.find(i);
            merged_map.entry(root).or_default().push(i);
        }

        // 5) Materialize output.
        let mut result: Vec<MergedCluster> = Vec::new();
        for (merged_id, (_, indices)) in merged_map.into_iter().enumerate() {
            let mut merged = MergedCluster {
                id: merged_id,
                source_clusters: Vec::new(),
                mentions: Vec::new(),
                canonical: None,
            };

            for idx in indices {
                let emb = &all_embeddings[idx];
                merged
                    .source_clusters
                    .push((emb.context_id, emb.cluster_id));

                if let Some(clusters) = local_clusters.get(&emb.context_id) {
                    if let Some(cluster) = clusters.iter().find(|c| c.id == emb.cluster_id) {
                        merged.mentions.extend(cluster.mentions.clone());
                        if merged.canonical.is_none() {
                            merged.canonical = cluster.canonical.clone();
                        }
                    }
                }
            }

            result.push(merged);
        }

        result
    }
}

/// Union-find structure for greedy merge closure.
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
}

impl UnionFind {
    fn new(n: usize) -> Self {
        Self {
            parent: (0..n).collect(),
            rank: vec![0; n],
        }
    }

    fn find(&mut self, mut x: usize) -> usize {
        while self.parent[x] != x {
            self.parent[x] = self.parent[self.parent[x]];
            x = self.parent[x];
        }
        x
    }

    fn union(&mut self, x: usize, y: usize) {
        let px = self.find(x);
        let py = self.find(y);
        if px == py {
            return;
        }
        match self.rank[px].cmp(&self.rank[py]) {
            std::cmp::Ordering::Less => self.parent[px] = py,
            std::cmp::Ordering::Greater => self.parent[py] = px,
            std::cmp::Ordering::Equal => {
                self.parent[py] = px;
                self.rank[px] += 1;
            }
        }
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ---- helpers ----

    fn make_mention(text: &str, start: usize, end: usize, context_id: usize) -> ClusterMention {
        ClusterMention {
            start,
            end,
            text: text.to_string(),
            context_id,
        }
    }

    fn make_cluster(
        id: usize,
        context_id: usize,
        mentions: Vec<(&str, usize, usize)>,
    ) -> LocalCluster {
        let mut cluster = LocalCluster::new(id, context_id);
        for (text, start, end) in mentions {
            cluster.add_mention(make_mention(text, start, end, context_id));
        }
        cluster
    }

    // =========================================================================
    // 1. HeuristicClusterEncoder
    // =========================================================================

    #[test]
    fn heuristic_encoder_output_shape() {
        let encoder = HeuristicClusterEncoder::new(64);
        let cluster = make_cluster(0, 0, vec![("John", 0, 4), ("he", 10, 12)]);
        let emb = encoder.encode_cluster(&cluster, None);

        assert_eq!(emb.embedding.len(), 64);
        assert_eq!(emb.cluster_id, 0);
        assert_eq!(emb.context_id, 0);
        assert_eq!(emb.mention_count, 2);
    }

    #[test]
    fn heuristic_encoder_embedding_dim() {
        let encoder = HeuristicClusterEncoder::new(128);
        assert_eq!(encoder.embedding_dim(), 128);
    }

    #[test]
    fn heuristic_encoder_same_mention_same_embedding() {
        let encoder = HeuristicClusterEncoder::new(64);
        let cluster1 = make_cluster(0, 0, vec![("John Smith", 0, 10)]);
        let cluster2 = make_cluster(1, 0, vec![("John Smith", 0, 10)]);

        let emb1 = encoder.encode_cluster(&cluster1, None);
        let emb2 = encoder.encode_cluster(&cluster2, None);

        // Same text -> same embedding (ignoring metadata)
        assert_eq!(emb1.embedding, emb2.embedding);
    }

    #[test]
    fn heuristic_encoder_different_mentions_different_embedding() {
        let encoder = HeuristicClusterEncoder::new(64);
        let cluster1 = make_cluster(0, 0, vec![("John Smith", 0, 10)]);
        let cluster2 = make_cluster(1, 0, vec![("completely different text", 0, 25)]);

        let emb1 = encoder.encode_cluster(&cluster1, None);
        let emb2 = encoder.encode_cluster(&cluster2, None);

        assert_ne!(emb1.embedding, emb2.embedding);
    }

    #[test]
    fn heuristic_encoder_normalized_output() {
        let encoder = HeuristicClusterEncoder::new(64);
        let cluster = make_cluster(0, 0, vec![("John Smith", 0, 10)]);
        let emb = encoder.encode_cluster(&cluster, None);

        let norm: f32 = emb.embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
        assert!((norm - 1.0).abs() < 1e-5, "norm={norm}, expected ~1.0");
    }

    #[test]
    fn heuristic_encoder_batch() {
        let encoder = HeuristicClusterEncoder::new(32);
        let clusters = vec![
            make_cluster(0, 0, vec![("A", 0, 1)]),
            make_cluster(1, 0, vec![("B", 2, 3)]),
            make_cluster(2, 0, vec![("C", 4, 5)]),
        ];
        let embeddings = encoder.encode_clusters(&clusters, None);
        assert_eq!(embeddings.len(), 3);
    }

    // =========================================================================
    // 2. CosineMergeScorer
    // =========================================================================

    #[test]
    fn cosine_scorer_identical_embeddings() {
        let scorer = CosineMergeScorer::new();
        let emb_a = ClusterEmbedding {
            embedding: vec![1.0, 0.0, 0.0],
            cluster_id: 0,
            context_id: 0,
            mention_count: 1,
        };
        let emb_b = ClusterEmbedding {
            embedding: vec![1.0, 0.0, 0.0],
            cluster_id: 1,
            context_id: 1,
            mention_count: 1,
        };
        let score = scorer.score(&emb_a, &emb_b);
        assert!((score - 1.0).abs() < 1e-5, "score={score}");
    }

    #[test]
    fn cosine_scorer_orthogonal_embeddings() {
        let scorer = CosineMergeScorer::new();
        let emb_a = ClusterEmbedding {
            embedding: vec![1.0, 0.0, 0.0],
            cluster_id: 0,
            context_id: 0,
            mention_count: 1,
        };
        let emb_b = ClusterEmbedding {
            embedding: vec![0.0, 1.0, 0.0],
            cluster_id: 1,
            context_id: 1,
            mention_count: 1,
        };
        let score = scorer.score(&emb_a, &emb_b);
        assert!(score.abs() < 1e-5, "score={score}, expected ~0.0");
    }

    #[test]
    fn cosine_scorer_mismatched_dims() {
        let scorer = CosineMergeScorer::new();
        let emb_a = ClusterEmbedding {
            embedding: vec![1.0, 0.0],
            cluster_id: 0,
            context_id: 0,
            mention_count: 1,
        };
        let emb_b = ClusterEmbedding {
            embedding: vec![1.0, 0.0, 0.0],
            cluster_id: 1,
            context_id: 1,
            mention_count: 1,
        };
        let score = scorer.score(&emb_a, &emb_b);
        assert_eq!(score, 0.0);
    }

    #[test]
    fn cosine_scorer_zero_embedding() {
        let scorer = CosineMergeScorer::new();
        let emb_a = ClusterEmbedding {
            embedding: vec![0.0, 0.0, 0.0],
            cluster_id: 0,
            context_id: 0,
            mention_count: 1,
        };
        let emb_b = ClusterEmbedding {
            embedding: vec![1.0, 0.0, 0.0],
            cluster_id: 1,
            context_id: 1,
            mention_count: 1,
        };
        let score = scorer.score(&emb_a, &emb_b);
        assert_eq!(score, 0.0);
    }

    // =========================================================================
    // 3. UnionFind / merge_clusters
    // =========================================================================

    #[test]
    fn union_find_no_merges() {
        let mut uf = UnionFind::new(5);
        // No unions -- each element is its own root
        for i in 0..5 {
            assert_eq!(uf.find(i), i);
        }
    }

    #[test]
    fn union_find_basic_merge() {
        let mut uf = UnionFind::new(5);
        uf.union(0, 1);
        uf.union(2, 3);
        // 0 and 1 should share a root
        assert_eq!(uf.find(0), uf.find(1));
        // 2 and 3 should share a root
        assert_eq!(uf.find(2), uf.find(3));
        // 0 and 2 should be in different sets
        assert_ne!(uf.find(0), uf.find(2));
        // 4 is alone
        assert_ne!(uf.find(4), uf.find(0));
        assert_ne!(uf.find(4), uf.find(2));
    }

    #[test]
    fn union_find_transitive_merge() {
        let mut uf = UnionFind::new(4);
        uf.union(0, 1);
        uf.union(1, 2);
        uf.union(2, 3);
        // All should share same root
        let root = uf.find(0);
        assert_eq!(uf.find(1), root);
        assert_eq!(uf.find(2), root);
        assert_eq!(uf.find(3), root);
    }

    #[test]
    fn cross_context_resolver_no_merge_below_threshold() {
        let encoder = HeuristicClusterEncoder::new(32);
        let scorer = CosineMergeScorer::new();
        let config = CrossContextConfig {
            threshold: 0.99,
            compare_same_context: false,
            max_clusters: None,
        };
        let resolver = CrossContextResolver::new(encoder, scorer, config);

        let mut local_clusters: HashMap<usize, Vec<LocalCluster>> = HashMap::new();
        // Two clusters in different contexts with completely different text
        local_clusters.insert(
            0,
            vec![make_cluster(0, 0, vec![("alpha beta gamma", 0, 16)])],
        );
        local_clusters.insert(
            1,
            vec![make_cluster(
                0,
                1,
                vec![("xyz completely different", 0, 23)],
            )],
        );

        let merged = resolver.resolve(&local_clusters, None);
        // With a very high threshold and very different text, they should not merge
        assert!(
            merged.len() >= 2,
            "expected >=2 clusters, got {}",
            merged.len()
        );
    }

    #[test]
    fn cross_context_resolver_identical_text_merges() {
        let encoder = HeuristicClusterEncoder::new(32);
        let scorer = CosineMergeScorer::new();
        let config = CrossContextConfig {
            threshold: 0.5,
            compare_same_context: false,
            max_clusters: None,
        };
        let resolver = CrossContextResolver::new(encoder, scorer, config);

        let mut local_clusters: HashMap<usize, Vec<LocalCluster>> = HashMap::new();
        // Identical mentions across two contexts -- should merge
        local_clusters.insert(0, vec![make_cluster(0, 0, vec![("John Smith", 0, 10)])]);
        local_clusters.insert(1, vec![make_cluster(0, 1, vec![("John Smith", 0, 10)])]);

        let merged = resolver.resolve(&local_clusters, None);
        // Should merge into a single cluster (same text -> cosine = 1.0 > 0.5 threshold)
        assert_eq!(
            merged.len(),
            1,
            "expected 1 merged cluster, got {}",
            merged.len()
        );
        assert_eq!(merged[0].mentions.len(), 2);
    }

    // =========================================================================
    // LocalCluster
    // =========================================================================

    #[test]
    fn local_cluster_compute_canonical() {
        let mut cluster = make_cluster(
            0,
            0,
            vec![("he", 10, 12), ("John Smith", 0, 10), ("him", 20, 23)],
        );
        cluster.compute_canonical();
        assert_eq!(cluster.canonical.as_deref(), Some("John Smith"));
    }

    #[test]
    fn local_cluster_compute_canonical_all_pronouns() {
        let mut cluster = make_cluster(0, 0, vec![("he", 0, 2), ("him", 5, 8)]);
        cluster.compute_canonical();
        // Falls back to first mention
        assert_eq!(cluster.canonical.as_deref(), Some("he"));
    }

    // =========================================================================
    // MergeScorer trait: get_merges and score_batch
    // =========================================================================

    #[test]
    fn cosine_scorer_get_merges() {
        let scorer = CosineMergeScorer::new();
        let a = vec![ClusterEmbedding {
            embedding: vec![1.0, 0.0],
            cluster_id: 0,
            context_id: 0,
            mention_count: 1,
        }];
        let b = vec![
            ClusterEmbedding {
                embedding: vec![1.0, 0.0], // identical to a
                cluster_id: 0,
                context_id: 1,
                mention_count: 1,
            },
            ClusterEmbedding {
                embedding: vec![0.0, 1.0], // orthogonal to a
                cluster_id: 1,
                context_id: 1,
                mention_count: 1,
            },
        ];
        let merges = scorer.get_merges(&a, &b, 0.5);
        // Only the first pair should be above threshold
        assert_eq!(merges.len(), 1, "merges: {merges:?}");
        assert_eq!(merges[0].0, 0); // index in a
        assert_eq!(merges[0].1, 0); // index in b
    }
}