vcp-core 4.2.0

Value Context Protocol (VCP) core types and parsing
Documentation
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
//! Schulze voting method for VCP consensus.
//!
//! Computes the strongest-path winner from ranked preference ballots.
//! Condorcet-consistent, clone-independent, used by Debian, Wikimedia,
//! and Creed Space.
//!
//! Algorithm:
//! 1. Build pairwise defeat matrix `d[i][j]` from ballots preferring i over j.
//! 2. Compute strongest paths `p[i][j]` via modified Floyd-Warshall.
//! 3. Rank candidates: i beats j when `p[i][j] > p[j][i]`.

use std::collections::{HashMap, HashSet};

/// Maximum candidates accepted by an election.
pub const MAX_CANDIDATES: usize = 256;

/// Maximum ballots retained by an election.
pub const MAX_BALLOTS: usize = 10_000;

/// Maximum Unicode scalar values in a candidate or voter identifier.
pub const MAX_IDENTIFIER_CHARS: usize = 256;

// ── Data types ─────────────────────────────────────────────────────────────

/// A ranked ballot from a stakeholder.
///
/// Rankings are expressed as ordered groups of candidates, best-first.
/// Each inner vec contains candidates of equal preference (ties).
/// Example: `vec![vec!["A"], vec!["B", "C"], vec!["D"]]` means A > B=C > D.
/// For simple rankings without ties: `vec![vec!["A"], vec!["B"], vec!["C"]]`.
///
/// This format matches the Python and TypeScript SDKs for cross-SDK parity.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Ballot {
    /// Voter identifier.
    pub voter_id: String,
    /// Ordered list of candidate groups, best-first.
    /// Each inner vec contains candidates of equal preference (ties).
    pub rankings: Vec<Vec<String>>,
}

impl Ballot {
    /// Create a simple ranked ballot (no ties).
    /// Each candidate gets its own group: `["A"] -> [["A"], ["B"], ["C"]]`.
    pub fn new(voter_id: impl Into<String>, ranking: Vec<String>) -> Self {
        let rankings = ranking.into_iter().map(|c| vec![c]).collect();
        Self {
            voter_id: voter_id.into(),
            rankings,
        }
    }

    /// Create a ballot with explicit tied groups.
    /// This is now the same as `new` with grouped rankings, kept for API compatibility.
    pub fn with_ties(voter_id: impl Into<String>, groups: Vec<Vec<String>>) -> Self {
        Self {
            voter_id: voter_id.into(),
            rankings: groups,
        }
    }
}

/// Pairwise comparison between two candidates.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PairwiseResult {
    pub candidate_a: String,
    pub candidate_b: String,
    pub a_preferred: i32,
    pub b_preferred: i32,
}

/// A candidate's position in the final Schulze ranking.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SchulzeRanking {
    pub candidate: String,
    /// 1-indexed rank, ties possible.
    pub rank: usize,
    /// Number of candidates this one beats.
    pub wins: usize,
    pub losses: usize,
}

/// Complete result of a Schulze election.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ElectionResult {
    /// Winner candidate, or None if no ballots.
    pub winner: Option<String>,
    /// Ordered ranking of all candidates.
    pub ranking: Vec<SchulzeRanking>,
    /// `d[i][j]` is the number of ballots preferring candidate i over candidate j.
    pub pairwise_matrix: Vec<Vec<i32>>,
    /// `p[i][j]` is the strength of the strongest path from i to j.
    pub strongest_paths: Vec<Vec<i32>>,
    /// Candidates in index order matching the matrices.
    pub candidates: Vec<String>,
    /// Total number of ballots cast.
    pub ballot_count: usize,
    /// Whether the winner is a Condorcet winner.
    pub has_condorcet_winner: bool,
    /// Pairs that tied in final ranking (deduplicated, sorted).
    pub ties: Vec<(String, String)>,
}

// ── SchulzeElection ────────────────────────────────────────────────────────

/// Schulze voting method for ranked preference aggregation.
pub struct SchulzeElection {
    candidates: Vec<String>,
    index: HashMap<String, usize>,
    ballots: Vec<Ballot>,
}

impl SchulzeElection {
    /// Create a new election with the given candidates.
    ///
    /// # Errors
    /// Returns an error if candidates are empty, duplicated, excessively
    /// numerous, or have empty or oversized identifiers.
    pub fn new(candidates: Vec<String>) -> Result<Self, &'static str> {
        if candidates.is_empty() {
            return Err("candidates must be non-empty");
        }
        if candidates.len() > MAX_CANDIDATES {
            return Err("too many candidates");
        }
        if candidates.iter().any(|candidate| {
            candidate.is_empty() || candidate.chars().count() > MAX_IDENTIFIER_CHARS
        }) {
            return Err("candidate identifiers must contain 1 to 256 characters");
        }
        let unique: HashSet<&str> = candidates.iter().map(String::as_str).collect();
        if unique.len() != candidates.len() {
            return Err("candidates must be unique");
        }
        let index: HashMap<String, usize> = candidates
            .iter()
            .enumerate()
            .map(|(i, c)| (c.clone(), i))
            .collect();
        Ok(Self {
            candidates,
            index,
            ballots: Vec::new(),
        })
    }

    /// Returns the list of candidates.
    pub fn candidates(&self) -> &[String] {
        &self.candidates
    }

    /// Returns the number of ballots cast.
    pub fn ballot_count(&self) -> usize {
        self.ballots.len()
    }

    /// Add a ranked ballot from a stakeholder.
    ///
    /// # Errors
    ///
    /// Returns an error without mutating the election if the ballot is empty,
    /// contains empty groups, duplicate or unknown candidates, has an invalid
    /// voter identifier, or would exceed the ballot resource limit.
    pub fn add_ballot(&mut self, ballot: Ballot) -> Result<(), &'static str> {
        if self.ballots.len() >= MAX_BALLOTS {
            return Err("too many ballots");
        }
        if ballot.voter_id.is_empty() || ballot.voter_id.chars().count() > MAX_IDENTIFIER_CHARS {
            return Err("voter identifiers must contain 1 to 256 characters");
        }
        if ballot.rankings.is_empty() {
            return Err("rankings must be non-empty");
        }
        let mut seen = HashSet::new();
        for group in &ballot.rankings {
            if group.is_empty() {
                return Err("ranking groups must be non-empty");
            }
            for candidate in group {
                if !self.index.contains_key(candidate) {
                    return Err("ballot contains an unknown candidate");
                }
                if !seen.insert(candidate.as_str()) {
                    return Err("ballot candidates must be unique");
                }
            }
        }
        self.ballots.push(ballot);
        Ok(())
    }

    /// Run the Schulze method. Returns the complete election result.
    pub fn compute(&self) -> ElectionResult {
        let n = self.candidates.len();

        if self.ballots.is_empty() {
            return ElectionResult {
                winner: None,
                ranking: Vec::new(),
                pairwise_matrix: vec![vec![0; n]; n],
                strongest_paths: vec![vec![0; n]; n],
                candidates: self.candidates.clone(),
                ballot_count: 0,
                has_condorcet_winner: false,
                ties: Vec::new(),
            };
        }

        let d = self.build_pairwise_matrix();
        let p = self.compute_strongest_paths(&d);
        let (ranking, ties) = self.determine_ranking(&p);

        let winner = ranking.first().map(|r| r.candidate.clone());
        let has_condorcet = winner.as_ref().is_some_and(|w| self.check_condorcet(&d, w));

        ElectionResult {
            winner,
            ranking,
            pairwise_matrix: d,
            strongest_paths: p,
            candidates: self.candidates.clone(),
            ballot_count: self.ballots.len(),
            has_condorcet_winner: has_condorcet,
            ties,
        }
    }

    /// Build pairwise defeat matrix.
    /// `d[i][j]` is the number of ballots that prefer candidate i over candidate j.
    fn build_pairwise_matrix(&self) -> Vec<Vec<i32>> {
        let n = self.candidates.len();
        let mut d = vec![vec![0i32; n]; n];

        for ballot in &self.ballots {
            self.apply_grouped_ballot(&mut d, ballot);
        }

        d
    }

    /// Apply a grouped ballot to the pairwise matrix.
    /// Each group in `ballot.rankings` contains candidates of equal preference.
    fn apply_grouped_ballot(&self, d: &mut [Vec<i32>], ballot: &Ballot) {
        let n = self.candidates.len();

        let mut position: HashMap<&str, usize> = HashMap::new();
        let mut rank = 0;
        for group in &ballot.rankings {
            for cid in group {
                if self.index.contains_key(cid.as_str()) {
                    position.insert(cid.as_str(), rank);
                }
            }
            rank += 1;
        }
        // Unranked candidates at the bottom
        for cid in &self.candidates {
            position.entry(cid.as_str()).or_insert(rank);
        }

        for i in 0..n {
            for j in (i + 1)..n {
                let pi = position[self.candidates[i].as_str()];
                let pj = position[self.candidates[j].as_str()];
                if pi < pj {
                    d[i][j] += 1;
                } else if pj < pi {
                    d[j][i] += 1;
                }
            }
        }
    }

    /// Compute strongest paths via modified Floyd-Warshall.
    ///
    /// `p[i][j]` is the strength of the strongest path from i to j.
    /// Path strength = minimum edge weight along the path.
    /// Only considers edges where `d[i][j] > d[j][i]` (net victories).
    #[allow(clippy::needless_range_loop)]
    fn compute_strongest_paths(&self, d: &[Vec<i32>]) -> Vec<Vec<i32>> {
        let n = self.candidates.len();
        let mut p = vec![vec![0i32; n]; n];

        // Initialize: direct edges where i beats j
        for i in 0..n {
            for j in 0..n {
                if i != j && d[i][j] > d[j][i] {
                    p[i][j] = d[i][j];
                }
            }
        }

        // Floyd-Warshall variant
        for k in 0..n {
            for i in 0..n {
                if i == k {
                    continue;
                }
                for j in 0..n {
                    if j == i || j == k {
                        continue;
                    }
                    let via_k = p[i][k].min(p[k][j]);
                    if via_k > p[i][j] {
                        p[i][j] = via_k;
                    }
                }
            }
        }

        p
    }

    /// Convert strongest path matrix to ordered ranking.
    #[allow(clippy::needless_range_loop)]
    fn determine_ranking(&self, p: &[Vec<i32>]) -> (Vec<SchulzeRanking>, Vec<(String, String)>) {
        let n = self.candidates.len();
        let mut ties: Vec<(String, String)> = Vec::new();

        // Count wins and losses for each candidate
        let mut wins = vec![0usize; n];
        let mut losses = vec![0usize; n];
        for i in 0..n {
            for j in 0..n {
                if i != j {
                    if p[i][j] > p[j][i] {
                        wins[i] += 1;
                        losses[j] += 1;
                    } else if p[i][j] == p[j][i] && p[i][j] > 0 {
                        ties.push((self.candidates[i].clone(), self.candidates[j].clone()));
                    }
                }
            }
        }

        // Also count ties where both paths are 0
        for i in 0..n {
            for j in (i + 1)..n {
                if p[i][j] == p[j][i] && p[i][j] == 0 {
                    let pair = (self.candidates[i].clone(), self.candidates[j].clone());
                    if !ties.contains(&pair) {
                        ties.push(pair);
                    }
                }
            }
        }

        // Sort indices by wins descending
        let mut indices: Vec<usize> = (0..n).collect();
        indices.sort_by(|&a, &b| wins[b].cmp(&wins[a]));

        // Assign ranks (1-indexed, ties get same rank)
        let mut rankings: Vec<SchulzeRanking> = Vec::with_capacity(n);
        let mut current_rank = 1;
        for (pos, &idx) in indices.iter().enumerate() {
            if pos > 0 {
                let prev_idx = indices[pos - 1];
                if wins[idx] < wins[prev_idx] {
                    current_rank = pos + 1;
                }
            }
            rankings.push(SchulzeRanking {
                candidate: self.candidates[idx].clone(),
                rank: current_rank,
                wins: wins[idx],
                losses: losses[idx],
            });
        }

        // Deduplicate ties
        let mut seen: HashSet<(String, String)> = HashSet::new();
        let mut deduped: Vec<(String, String)> = Vec::new();
        for (a, b) in ties {
            let key = if a < b {
                (a.clone(), b.clone())
            } else {
                (b.clone(), a.clone())
            };
            if seen.insert(key.clone()) {
                deduped.push(key);
            }
        }

        (rankings, deduped)
    }

    /// Check if the winner is a Condorcet winner (beats all others pairwise).
    #[allow(clippy::needless_range_loop)]
    fn check_condorcet(&self, d: &[Vec<i32>], winner: &str) -> bool {
        let Some(&wi) = self.index.get(winner) else {
            return false;
        };
        for j in 0..self.candidates.len() {
            if j != wi && d[wi][j] <= d[j][wi] {
                return false;
            }
        }
        true
    }
}

// ── Tests ──────────────────────────────────────────────────────────────────

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

    fn cands(names: &[&str]) -> Vec<String> {
        names.iter().map(ToString::to_string).collect()
    }

    #[test]
    fn test_empty_candidates() {
        assert!(SchulzeElection::new(Vec::new()).is_err());
    }

    #[test]
    fn test_duplicate_candidates() {
        let result = SchulzeElection::new(cands(&["a", "b", "a"]));
        assert!(result.is_err());
    }

    #[test]
    fn election_candidate_limits_are_inclusive() {
        let maximum: Vec<String> = (0..MAX_CANDIDATES)
            .map(|index| format!("c{index}"))
            .collect();
        assert!(SchulzeElection::new(maximum).is_ok());

        let excessive: Vec<String> = (0..=MAX_CANDIDATES)
            .map(|index| format!("c{index}"))
            .collect();
        assert_eq!(
            SchulzeElection::new(excessive).err(),
            Some("too many candidates")
        );
        assert!(SchulzeElection::new(vec![String::new()]).is_err());
        assert!(SchulzeElection::new(vec!["x".repeat(MAX_IDENTIFIER_CHARS + 1)]).is_err());
    }

    #[test]
    fn test_no_ballots() {
        let election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        let result = election.compute();
        assert!(result.winner.is_none());
        assert_eq!(result.ballot_count, 0);
    }

    #[test]
    fn test_single_ballot() {
        let mut election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        election
            .add_ballot(Ballot::new("v1", cands(&["b", "a", "c"])))
            .unwrap();
        let result = election.compute();
        assert_eq!(result.winner.as_deref(), Some("b"));
        assert_eq!(result.ballot_count, 1);
        assert!(result.has_condorcet_winner);
    }

    #[test]
    fn unknown_ballot_candidate_is_rejected_without_state_mutation() {
        let mut election = SchulzeElection::new(cands(&["a", "b"])).unwrap();

        assert_eq!(
            election.add_ballot(Ballot::new("v1", cands(&["a", "typo"]))),
            Err("ballot contains an unknown candidate")
        );
        assert_eq!(election.ballot_count(), 0);
        assert!(election.compute().winner.is_none());
    }

    #[test]
    fn malformed_ballots_are_rejected_without_state_mutation() {
        let mut election = SchulzeElection::new(cands(&["a", "b"])).unwrap();
        let malformed = [
            Ballot::with_ties("v1", Vec::new()),
            Ballot::with_ties("v1", vec![Vec::new()]),
            Ballot::with_ties("v1", vec![cands(&["a"]), cands(&["a"])]),
            Ballot::new("", cands(&["a"])),
            Ballot::new("v".repeat(MAX_IDENTIFIER_CHARS + 1), cands(&["a"])),
        ];

        for ballot in malformed {
            assert!(election.add_ballot(ballot).is_err());
            assert_eq!(election.ballot_count(), 0);
        }
    }

    #[test]
    fn ballot_limit_is_enforced_before_mutation() {
        let mut election = SchulzeElection::new(cands(&["a"])).unwrap();
        election.ballots = vec![Ballot::new("v", cands(&["a"])); MAX_BALLOTS];

        assert_eq!(
            election.add_ballot(Ballot::new("last", cands(&["a"]))),
            Err("too many ballots")
        );
        assert_eq!(election.ballot_count(), MAX_BALLOTS);
    }

    #[test]
    fn test_condorcet_winner() {
        // b is the Condorcet winner (preferred by majority against each other)
        let mut election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        election
            .add_ballot(Ballot::new("v1", cands(&["b", "a", "c"])))
            .unwrap();
        election
            .add_ballot(Ballot::new("v2", cands(&["b", "c", "a"])))
            .unwrap();
        election
            .add_ballot(Ballot::new("v3", cands(&["a", "b", "c"])))
            .unwrap();
        let result = election.compute();
        assert_eq!(result.winner.as_deref(), Some("b"));
        assert!(result.has_condorcet_winner);
    }

    #[test]
    fn test_tied_groups_ballot() {
        let mut election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        // a and b are tied at top, c is below
        election
            .add_ballot(Ballot::with_ties(
                "v1",
                vec![cands(&["a", "b"]), cands(&["c"])],
            ))
            .unwrap();
        let result = election.compute();
        // Both a and b should beat c but not each other
        let a_idx = 0;
        let b_idx = 1;
        let c_idx = 2;
        assert_eq!(result.pairwise_matrix[a_idx][c_idx], 1);
        assert_eq!(result.pairwise_matrix[b_idx][c_idx], 1);
        assert_eq!(result.pairwise_matrix[a_idx][b_idx], 0);
        assert_eq!(result.pairwise_matrix[b_idx][a_idx], 0);
    }

    #[test]
    fn test_strongest_paths_match_python() {
        // Classic 4-candidate Schulze example
        let mut election = SchulzeElection::new(cands(&["a", "b", "c", "d"])).unwrap();
        // 3 voters: a > b > c > d
        for _ in 0..3 {
            election
                .add_ballot(Ballot::new("v", cands(&["a", "b", "c", "d"])))
                .unwrap();
        }
        // 2 voters: d > c > b > a
        for _ in 0..2 {
            election
                .add_ballot(Ballot::new("v", cands(&["d", "c", "b", "a"])))
                .unwrap();
        }
        let result = election.compute();

        // a beats all 3>2, so a is the Condorcet winner
        assert_eq!(result.winner.as_deref(), Some("a"));
        assert!(result.has_condorcet_winner);

        // Verify pairwise: a beats b,c,d 3-2
        assert_eq!(result.pairwise_matrix[0][1], 3); // a>b
        assert_eq!(result.pairwise_matrix[1][0], 2); // b>a
    }

    #[test]
    fn test_schulze_ranking_order() {
        let mut election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        election
            .add_ballot(Ballot::new("v1", cands(&["c", "b", "a"])))
            .unwrap();
        election
            .add_ballot(Ballot::new("v2", cands(&["c", "a", "b"])))
            .unwrap();
        election
            .add_ballot(Ballot::new("v3", cands(&["b", "c", "a"])))
            .unwrap();
        let result = election.compute();

        // c wins 2 first-place votes, should be top
        assert_eq!(result.winner.as_deref(), Some("c"));
        assert_eq!(result.ranking[0].candidate, "c");
        assert_eq!(result.ranking[0].rank, 1);
    }

    #[test]
    fn test_unranked_candidates_at_bottom() {
        let mut election = SchulzeElection::new(cands(&["a", "b", "c"])).unwrap();
        // Only ranks "a", so b and c are tied at bottom
        election
            .add_ballot(Ballot::new("v1", cands(&["a"])))
            .unwrap();
        let result = election.compute();
        assert_eq!(result.winner.as_deref(), Some("a"));
        // a should beat both b and c
        assert_eq!(result.pairwise_matrix[0][1], 1); // a>b
        assert_eq!(result.pairwise_matrix[0][2], 1); // a>c
                                                     // b and c tied (both unranked)
        assert_eq!(result.pairwise_matrix[1][2], 0);
        assert_eq!(result.pairwise_matrix[2][1], 0);
    }
}