constitution · epochs · watch · epoch 3

comparison

c_9e1ff4fc0186 (tommy-mor) vs c_48aeaf9b52c3 (tommy-mor)

download prompt · raw event · cmp_45aac340cca702

council reasoning

~anthropic/claude-sonnet-latest · winner B · 85:15 · permalink

Side B fixes a real, subtle correctness bug in the ranking algorithm (wrong divisor causing bipartite oscillation on star topologies), grounds the fix in the cited paper's actual definition, and adds targeted Rust and Clojure regression tests/fixtures proving the fix. Side A is almost entirely rustfmt/whitespace churn plus a tiny CSS dedupe and toolchain pin, which is useful housekeeping but contributes no functional value and is mostly noise/formatting.

~x-ai/grok-latest · winner B · 1:12 · permalink

Commit B fixes a real correctness bug in the core Rank Centrality scoring (wrong d_max divisor causing bipartite oscillation and uniform scores on star topologies), aligns the math with the cited paper, and adds durable Rust + Clojure regression tests with fixtures. Commit A is almost entirely rustfmt whitespace/import churn plus minor tooling pins and a trivial CSS dedup, which adds negligible lasting product value.

openai/gpt-chat-latest · winner B · 20:1 · permalink

Side B fixes a substantive correctness bug in `compute_scores_from_edges` by switching the Rank Centrality normalization from summed edge weights to the canonical degree-based `d_max`, preventing oscillating bipartite Markov chains and producing correct rankings for star topologies. It also adds targeted Rust and end-to-end regression tests with ranking fixtures, whereas Side A is overwhelmingly rustfmt-driven reformatting plus minor tooling changes (pinning rustfmt/clippy, VS Code settings, and a small CSS cleanup) with little lasting behavioral impact.

sides

A — c_9e1ff4fc0186 (tommy-mor)

message

[2a94401b] Run rustfmt workspace-wide and fix lint tooling.

Pin rustfmt and clippy in rust-toolchain.toml after a broken component install, merge a duplicate vote-slider CSS rule, and add VS Code settings so rust-analyzer uses the project toolchain.

Co-authored-by: Cursor <cursoragent@cursor.com>

diff preview

diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 0000000000000000000000000000000000000000..98ebd754a6d5a972550506c69c5a10c10e3210b6
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,8 @@
+{
+  "rust-analyzer.rustc.source": "discover",
+  "rust-analyzer.check.command": "check",
+  "rust-analyzer.procMacro.enable": true,
+  "rust-analyzer.cargo.extraEnv": {
+    "RUSTUP_TOOLCHAIN": "1.88.0"
+  }
+}
diff --git a/durable/examples/combined_example.rs b/durable/examples/combined_example.rs
index 626a6e1cf7e3c9c26f9f2edc58950d9bc31ec67e..6e9cb3210714d74c9a2cc0ed4f87e1b8d84788da 100644
--- a/durable/examples/combined_example.rs
+++ b/durable/examples/combined_example.rs
@@ -1,5 +1,5 @@
 use durable::{Db, DurableMap, DurableVec};
-use serde::{Serialize, Deserialize};
+use serde::{Deserialize, Serialize};
 use std::time::{SystemTime, UNIX_EPOCH};
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -28,36 +28,48 @@ fn get_timestamp() -> u64 {
 fn main() -> Result<(), Box<dyn std::error::Error>> {
     // Open or create a database
     let db = Db::open("chat_db")?;
-    
+
     // Create our collections
     let mut users = DurableMap::<String, User>::new(&db, "users")?;
     let mut messages = DurableVec::<Message>::new(&db, "messages")?;
     let mut user_message_indices = DurableMap::<String, Vec<usize>>::new(&db, "user_messages")?;
-    
+
     // Create some users
-    users.insert("alice".to_string(), User {
-        username: "alice".to_string(),
-        display_name: "Alice Smith".to_string(),
-        message_count: 0,
-    })?;
-    
-    users.insert("bob".to_string(), User {
-        username: "bob".to_string(),
-        display_name: "Bob Johnson".to_string(),
-        message_count: 0,
-    })?;
-    
-    users.insert("charlie".to_string(), User {
-        username: "charlie".to_string(),
-        display_name: "Charlie Brown".to_string(),
-        message_count: 0,
-    })?;
-    
+    users.insert(
+        "alice".to_string(),
+        User {
+            username: "alice".to_string(),
+            display_name: "Alice Smith".to_string(),
+            message_count: 0,
+        },
+    )?;
+
+    users.insert(
+        "bob".to_string(),
+        User {
+            username: "bob".to_string(),
+            display_name: "Bob Johnson".to_string(),
+            message_count: 0,
+        },
+    )?;
+
+    users.insert(
+        "charlie".to_string(),
+        User {
+            username: "charlie".to_string(),
+            display_name: "Charlie Brown".to_string(),
+            message_count: 0,
+        },
+    )?;
+
     // Helper to send a message
-    let send_message = |from: &str, to: &str, content: &str, 
+    let send_message = |from: &str,
+                        to: &str,
+                        content: &str,
                         messages: &mut DurableVec<Message>,
                         users: &mut DurableMap<String, User>,
-                        indices: &mut DurableMap<String, Vec<usize>>| -> Result<(), Box<dyn std::error::Error>> {
+                        indices: &mut DurableMap<String, Vec<usize>>|
+     -> Result<(), Box<dyn std::error::Error>> {
         // Create message
         let msg_id = messages.len()? as u64;
         let message = Message {
@@ -67,61 +79,93 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
             content: content.to_string(),
             timestamp: get_timestamp(),
         };
-        
+
         // Store message
         messages.push(message)?;
         let msg_index = messages.len()? - 1;
-        
+
         // Update sender's message count
         if let Some(mut sender) = users.get(&from.to_string())? {
             sender.message_count += 1;
             users.insert(from.to_string(), sender)?;
         }
-        
+
         // Track message indices for recipient
         let mut recipient_indices = indices.get(&to.to_string())?.unwrap_or_default();
         recipient_indices.push(msg_index);
         indices.insert(to.to_string(), recipient_indices)?;
-        
+
         Ok(())
     };
-    
+
     // Send some messages
     println!("💬 Chat Application Demo\n");
     println!("Sending messages...");
-    
-    send_message("alice", "bob", "Hey Bob, how's the Durable library coming along?", 
-                 &mut messages, &mut users, &mut user_message_indices)?;
-    
-    send_message("bob", "alice", "It's going great! We have DurableVec and DurableMap working!", 
-                 &mut messages, &mut users, &mut user_message_indices)?;
-    
-    send_message("charlie", "alice", "That sounds awesome! Can I help with testing?", 
-                 &mut messages, &mut users, &mut user_message_indices)?;
-    
-    send_message("alice", "charlie", "Absolutely! The more testing the better!", 
-                 &mut messages, &mut users, &mut user_message_indices)?;
-    
-    send_message("bob", "charlie", "Check out the examples directory for usage patterns", 
-                 &mut messages, &mut users, &mut user_message_indices)?;
-    
+
+    send_message(
+        "alice",
+        "bob",
+        "Hey Bob, how's the Durable library coming along?",
+        &mut messages,
+        &mut users,
+        &mut user_message_indices,
+    )?;
+
+    send_message(
+        "bob",
+        "alice",
+        "It's going great! We have DurableVec and DurableMap working!",
+        &mut messages,
+        &mut users,
+        &mut user_message_indices,
+    )?;
+
+    send_message(
+        "charlie",
+        "alice",
+        "That sounds awesome! Can I help with testing?",
+        &mut messages,
+        &mut users,
+        &mut user_message_indices,
+    )?;
+
+    send_message(
+        "alice",
+        "charlie",
+        "Absolutely! The more testing the better!",
+        &mut messages,
+        &mut users,
+        &mut user_message_indices,
+    )?;
+
+    send_message(
+        "bob",
+        "charlie",
+        "Check out the examples directory for usage patterns",
+        &mut messages,
+        &mut users,
+        &mut user_message_indices,
+    )?;
+
     // Display all users and their message counts
     println!("\n👥 Users:");
     let mut all_users = users.to_vec()?;
     all_users.sort_by_key(|(username, _)| username.clone());
-    
+
     for (username, user) in all_users {
-        println!("  {} ({}) - {} messages sent", 
-                 user.display_name, username, user.message_count);
+        println!(
+            "  {} ({}) - {} messages sent",
+            user.display_name, username, user.message_count
+        );
     }
-    
+
     // Display all messages
     println!("\n📨 All messages:");
     for (i, msg) in messages.iter()?.enumerate() {
         let msg = msg?;
         println!("  [{}] {} → {}: {}", i, msg.from, msg.to, msg.content);
     }
-    
+
     // Show inbox for each user
     println!("\n📥 User inboxes:");
     for item in users.iter() {
@@ -135,26 +179,26 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
             }
         }
     }
-    
+
     // Statistics
     println!("\n📊 Statistics:");
     println!("  Total users: {}", users.len()?);
     println!("  Total messages: {}", messages.len()?);
-    
+
     // Demonstrate persistence
     println!("\n💾 Data has been persisted to disk!");
     println!("  Database location: ./chat_db");
-    
+
     // Clean up
     drop(messages);
     drop(users);
     drop(user_message_indices);
     drop(db);
-    
+
     // Remove the database for this example
     std::fs::remove_dir_all("chat_db").ok();
-    
+
     println!("\n✅ Example completed!");
-    
+
     Ok(())
-} 
\ No newline at end of file
+}
diff --git a/durable/examples/map_example.rs b/durable/examples/map_example.rs
index 08b8f2c8826caf53c4c20b422a540c92f6624029..1d9c4a14b0f4cfe39ade84ebb1f1a14033e8ff1b 100644
--- a/durable/examples/map_example.rs
+++ b/durable/examples/map_example.rs
@@ -1,5 +1,5 @@
 use durable::{Db, DurableMap};
-use serde::{Serialize, Deserialize};
+use serde::{Deserialize, Serialize};
 
 #[derive(Debug, Clone, Serialize, Deserialize)]
 struct UserProfile {
@@ -11,10 +11,10 @@ struct UserProfile {
 fn main() -> Result<(), Box<dyn std::error::Error>> {
     // Open or create a database
     let db = Db::open("example_db")?;
-    
+
     // Create a persistent map of user profiles
     let mut users = DurableMap::<String, UserProfile>::new(&db, "users")?;
-    
+
     // Insert some users
     // Using put() when we don't need the old value - more efficient!
     users.put(
@@ -25,7 +25,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
             score: 1500,
         },
     )?;
-    
+
     users.put(
         "bob".to_string(),
         UserProfile {
@@ -34,7 +34,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
             score: 1200,
         },
     )?;
-    
+
     // Using insert() when we might need the old value
     let old_charlie = users.insert(
         "charlie".to_string(),
@@ -44,21 +44,24 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
             score: 1800,
         },
     )?;
-    
+
     if old_charlie.is_some() {
         println!("Replaced existing charlie entry");
     }
-    
+
     println!("Total users: {}", users.len()?);
-    
+
     // Look up a specific user
     if let Some(alice) = users.get(&"alice".to_string())? {
         println!("\nAlice's profile: {:?}", alice);
     }
-    
+
     // Check if a user exists
-    println!("\nDoes 'david' exist? {}", users.contains_key(&"david".to_string())?);
-    
+    println!(
+        "\nDoes 'david' exist? {}",
+        users.contains_key(&"david".to_string())?
+    );
+
     // Update a user's score
     if let Some(mut bob) = users.get(&"bob".to_string())? {
         bob.score += 100;
@@ -66,34 +69,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
         users.put("bob".to_string(), bob)?;
         println!("Updated Bob's score!");
     }
-    
+
     // Iterate over all users
     println!("\nAll users (sorted by username):");
     let mut all_users = users.to_vec()?;
     all_users.sort_by_key(|(username, _)| username.clone());
-    
+
     for (username, profile) in all_users {
-        println!("  {} ({}) - Score: {}", username, profile.email, profile.score);
+        println!(
+            "  {} ({}) - Score: {}",
+            username, profile.email, profile.score
+        );
     }
-    
+
     // Get just the usernames
     let mut usernames = users.keys_vec()?;
     usernames.sort();
     println!("\nAll usernames: {:?}", usernames);
-    
+
     // Find the highest scoring user
     let profiles = users.values_vec()?;
     if let Some(top_user) = profiles.iter().max_by_key(|p| p.score) {
-        println!("\nTop scorer: {} with {} points", top_user.name, top_user.score);
+        println!(
+            "\nTop scorer: {} with {} points",
+            top_user.name, top_user.score
+        );
     }
-    
+
     // Remove a user
     if let Some(removed) = users.remove(&"charlie".to_string())? {
         println!("\nRemoved user: {}", removed.name);
         println!("Users remaining: {}", users.len()?);
     }
-    
+
     println!("\nData has been persisted to disk.");
-    
+
     Ok(())
-} 
\ No newline at end of file
+}
diff --git a/durable/examples/nested_example.rs b/durable/examples/nested_example.rs
index 3b880f2c8b8ad2633d4b5fcf2016652216c9de8e..f16090cf6fb854ac7a1b00acfd31fbd12c25dbce 100644
--- a/durable/examples/nested_example.rs
+++ b/durable/examples/nested_example.rs
@@ -3,27 +3,31 @@ use durable::{Db, DurableMap, DurableVec};
 fn main() -> Result<(), Box<dyn std::error::Error>> {
     // Open a database
     let db = Db::open("nested_example_db")?;
-    
+
     // Create a map where each user has a list of posts
-    let user_posts: DurableMap<String, DurableVec<String>> = DurableMap::new_nested(&db, "user_posts");
-    
+    let user_posts: DurableMap<String, DurableVec<String>> =
+        DurableMap::new

… preview truncated; 96,900 characters omitted

download full diff A

B — c_48aeaf9b52c3 (tommy-mor)

message

[595b3850] Fix star-topology ranking by using degree-based d_max (#146).

A pure forward star at the default `>` ratio (2:1) produced uniform 1/3
scores, and the alphabetical-fallback sort placed the unambiguous winner
last. Root cause: `compute_scores_from_edges` divided by the max sum of
pairwise-normalized weights, so every node ended up with P_ii = 0 — a
bipartite Markov chain whose power iteration oscillated and, after the
configured even iteration count, returned to the uniform initial state.

Switch the divisor to the unweighted max neighbor degree, matching the
canonical Rank Centrality definition in Negahban–Oh–Shah 2012 §3.1
(arXiv:1209.1688, eq. defP and the d_max definition in §6). This gives
every non-saturated node a positive self-loop, makes the chain aperiodic,
and converges the star to π_zebra = 1/2, π_alpha = π_beta = 1/4.

Add Rust regression test and a Clojure test that drives the sorterc
binary against four .sorter fixtures (star, inverse star, chain, cycle).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

diff preview

diff --git a/server/src/ranking.rs b/server/src/ranking.rs
index 3710c9f64437f5bef3b2121905b6f3bcb7611047..38e6d09b4370e5f8cbae09c0e5760b4e7f1ef7db 100644
--- a/server/src/ranking.rs
+++ b/server/src/ranking.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
 
 use crate::path_types::ItemId;
 use crate::reducer::GroupState;
@@ -143,23 +143,35 @@ fn compute_scores_from_edges(n: usize, edges: impl Iterator<Item = ((usize, usiz
         }
     }
 
+    // Rank Centrality (Negahban, Oh, Shah 2012, §3.1):
+    //   P_ij = (1/d_max) * A_ij           for i ≠ j compared
+    //   P_ii = 1 - (1/d_max) * Σ_k A_ik
+    // where d_i is the *degree* (number of distinct neighbors compared) and
+    // d_max = max_i d_i. Using the unweighted degree — not the sum of
+    // pairwise-normalized weights — is what guarantees aperiodicity: it
+    // forces P_ii > 0 for every non-maximum-degree node, and for max-degree
+    // nodes whenever any neighbor weight is below 1 (i.e. not a unanimous
+    // loss). Without this, regular comparison graphs (e.g. a pure star at
+    // ratio 2:1) produce a bipartite chain that oscillates instead of
+    // converging — see issue #146.
     let mut out_edges: Vec<Vec<(usize, f64)>> = vec![Vec::new(); n];
-    let mut out_deg: Vec<f64> = vec![0.0; n];
+    let mut neighbors: Vec<HashSet<usize>> = vec![HashSet::new(); n];
 
     for ((src, dst), w) in &normalized {
         out_edges[*src].push((*dst, *w));
-        out_deg[*src] += w;
+        neighbors[*src].insert(*dst);
+        neighbors[*dst].insert(*src);
     }
 
-    let mut max_out = 0.0f64;
-    for &d in &out_deg {
-        if d > max_out {
-            max_out = d;
-        }
-    }
-    if max_out <= 1e-12 {
+    let weight_sum: Vec<f64> = out_edges
+        .iter()
+        .map(|es| es.iter().map(|(_, w)| *w).sum())
+        .collect();
+    let d_max = neighbors.iter().map(|s| s.len()).max().unwrap_or(0);
+    if d_max == 0 {
         return vec![1.0 / n as f64; n];
     }
+    let d_max_f = d_max as f64;
 
     let mut scores = vec![1.0 / n as f64; n];
     let mut next = vec![0.0f64; n];
@@ -167,14 +179,14 @@ fn compute_scores_from_edges(n: usize, edges: impl Iterator<Item = ((usize, usiz
     for _ in 0..max_iters {
         next.fill(0.0);
         for i in 0..n {
-            let stay_prob = (max_out - out_deg[i]) / max_out;
+            let stay_prob = (d_max_f - weight_sum[i]) / d_max_f;
             next[i] += scores[i] * stay_prob;
 
             if out_edges[i].is_empty() {
                 continue;
             }
             for &(dst, w) in &out_edges[i] {
-                next[dst] += scores[i] * (w / max_out);
+                next[dst] += scores[i] * (w / d_max_f);
             }
         }
 
@@ -270,6 +282,38 @@ mod tests {
         }
     }
 
+    /// Regression for issue #146: pure forward star at default `>` ratio (2:1).
+    /// Under the old (sum-of-weights) divisor every node had P_ii = 0 and the
+    /// chain was bipartite; power iteration oscillated and returned the
+    /// uniform initial distribution after an even number of steps. Using the
+    /// paper's degree-based d_max gives every node a positive self-loop and
+    /// the chain converges to the correct stationary distribution.
+    #[test]
+    fn star_topology_winner_at_top_via_subset() {
+        let mut g = mk_group();
+        g.apply_vote(vote(1, "zebra", "alpha", 2, 1));
+        g.apply_vote(vote(2, "zebra", "beta", 2, 1));
+
+        let mut items: Vec<(usize, String)> = g
+            .idx_to_item
+            .iter()
+            .enumerate()
+            .map(|(i, it)| (i, it.as_str().to_string()))
+            .collect();
+        items.sort_by(|a, b| a.1.cmp(&b.1));
+        let idxs: Vec<usize> = items.iter().map(|(i, _)| *i).collect();
+
+        let ranked = ranked_items_subset(&g, &idxs, 10000, 1e-8);
+        for r in &ranked {
+            eprintln!("{}: {}", r.item.as_str(), r.score);
+        }
+        assert_eq!(
+            ranked[0].item.as_str(),
+            "https://slug.social/zebra",
+            "zebra won both votes and should rank #1"
+        );
+    }
+
     #[test]
     fn group_ranking_cache_dirty_flow() {
         let mut g = mk_group();
diff --git a/test/fixtures/ranking/chain.sorter b/test/fixtures/ranking/chain.sorter
new file mode 100644
index 0000000000000000000000000000000000000000..912a96bdc08f631be27f3c9afc7e05004a2457c0
--- /dev/null
+++ b/test/fixtures/ranking/chain.sorter
@@ -0,0 +1,10 @@
+#t3
+
+~/t3/a { head of chain }
+~/t3/b { middle }
+~/t3/c { tail }
+
+{ a > b }
+~/t3/a > ~/t3/b
+{ b > c }
+~/t3/b > ~/t3/c
diff --git a/test/fixtures/ranking/cycle.sorter b/test/fixtures/ranking/cycle.sorter
new file mode 100644
index 0000000000000000000000000000000000000000..771731ae176e5d77e00ab89767ff2d7465bb7c6b
--- /dev/null
+++ b/test/fixtures/ranking/cycle.sorter
@@ -0,0 +1,12 @@
+#t4
+
+~/t4/a { node a }
+~/t4/b { node b }
+~/t4/c { node c }
+
+{ a > b }
+~/t4/a > ~/t4/b
+{ b > c }
+~/t4/b > ~/t4/c
+{ c > a }
+~/t4/c > ~/t4/a
diff --git a/test/fixtures/ranking/star.sorter b/test/fixtures/ranking/star.sorter
new file mode 100644
index 0000000000000000000000000000000000000000..135c9f9097d57b73c7ab18fac737ed3598d76fbe
--- /dev/null
+++ b/test/fixtures/ranking/star.sorter
@@ -0,0 +1,11 @@
+#repro
+
+~/repro/zebra { winner — beats both others }
+~/repro/alpha { loser — alphabetically first }
+~/repro/beta { loser — alphabetically middle }
+
+{ zebra beats alpha }
+~/repro/zebra > ~/repro/alpha
+
+{ zebra beats beta }
+~/repro/zebra > ~/repro/beta
diff --git a/test/fixtures/ranking/star_inverse.sorter b/test/fixtures/ranking/star_inverse.sorter
new file mode 100644
index 0000000000000000000000000000000000000000..dab842fa924e5124865ee216b9565f6c7471c812
--- /dev/null
+++ b/test/fixtures/ranking/star_inverse.sorter
@@ -0,0 +1,11 @@
+#t2
+
+~/t2/win { source of incoming edges (loses both) }
+~/t2/loss-a { winner }
+~/t2/loss-b { winner }
+
+{ loss-a beats win }
+~/t2/loss-a > ~/t2/win
+
+{ loss-b beats win }
+~/t2/loss-b > ~/t2/win
diff --git a/test/ranking.clj b/test/ranking.clj
new file mode 100644
index 0000000000000000000000000000000000000000..e1358783a84a264ee633bd79151ba29750b717cf
--- /dev/null
+++ b/test/ranking.clj
@@ -0,0 +1,74 @@
+(ns test.ranking
+  "Drives sorterc on .sorter fixtures and asserts ranking properties.
+
+   Regression coverage for issue #146 — pure forward star at default ratio
+   (2:1 for `>`) used to produce tied uniform scores because the random walk
+   on the normalized edge weights was bipartite. Fixed by switching to the
+   degree-based d_max from Negahban–Oh–Shah rank centrality (§3.1)."
+  (:require [clojure.test :refer [deftest is testing]]
+            [babashka.process :as p]
+            [cheshire.core :as json]
+            [clojure.java.io :as io]))
+
+(def sorterc-bin
+  "Path to the locally-built sorterc binary. Builds on demand if missing."
+  (let [dbg     "target/debug/sorterc"
+        release "target/release/sorterc"]
+    (cond
+      (.exists (io/file release)) release
+      (.exists (io/file dbg))     dbg
+      :else
+      (do (println "building sorterc…")
+          (let [r (p/shell {:out :string :err :string :continue true}
+                           "cargo build -p sorterc")]
+            (when-not (zero? (:exit r))
+              (throw (ex-info "cargo build -p sorterc failed"
+                              {:stderr (:err r)}))))
+          dbg))))
+
+(defn compile-sorter [fixture-path]
+  (let [{:keys [out exit]} (p/shell {:out :string :err :string :continue true}
+                                    sorterc-bin "compile" fixture-path)]
+    (when-not (zero? exit)
+      (throw (ex-info "sorterc exit nonzero" {:fixture fixture-path :out out})))
+    (json/parse-string out true)))
+
+(defn first-component-ranking [result]
+  (-> result :rankings first :components first :ranking))
+
+(defn item-leaf [item]
+  (last (clojure.string/split item #"/")))
+
+(deftest chain-ranks-head-first
+  (let [ranking (first-component-ranking (compile-sorter "test/fixtures/ranking/chain.sorter"))
+        names   (mapv (comp item-leaf :item) ranking)]
+    (is (= ["a" "b" "c"] names)
+        "chain a>b>c should rank a, b, c in order")
+    (is (apply > (map :score ranking))
+        "scores should attenuate strictly down the chain")))
+
+(deftest inverse-star-puts-winners-on-top
+  (let [ranking (first-component-ranking (compile-sorter "test/fixtures/ranking/star_inverse.sorter"))
+        names   (mapv (comp item-leaf :item) ranking)]
+    (is (= "win" (last names))
+        "the item that lost to both others should be ranked last")))
+
+(deftest cycle-produces-uniform-scores
+  (let [ranking (first-component-ranking (compile-sorter "test/fixtures/ranking/cycle.sorter"))
+        scores  (map :score ranking)]
+    (is (every? #(< (Math/abs (- % 1/3)) 1e-3) scores)
+        "a perfectly symmetric 3-cycle should give every node ~1/3")))
+
+(deftest star-topology-winner-at-top
+  ;; Issue #146 regression: source-only star at default `>` ratio (2:1).
+  ;; Pre-fix produced uniform 1/3 scores; alphabetical fallback put the
+  ;; unambiguous winner at the bottom. Post-fix the chain is aperiodic and
+  ;; converges to π_zebra = 1/2, π_alpha = π_beta = 1/4.
+  (let [ranking (first-component-ranking (compile-sorter "test/fixtures/ranking/star.sorter"))
+        names   (mapv (comp item-leaf :item) ranking)
+        by-name (into {} (map (juxt (comp item-leaf :item) :score) ranking))]
+    (is (= "zebra" (first names))
+        "zebra won both votes and should rank #1")
+    (is (< (Math/abs (- (by-name "zebra") 0.5)) 1e-3))
+    (is (< (Math/abs (- (by-name "alpha") 0.25)) 1e-3))
+    (is (< (Math/abs (- (by-name "beta") 0.25)) 1e-3))))

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.