{"messages":[{"content":"You are a constitutional council ranking individual git commits for ownership allocation.\n\nCompare these two commits. Decide which contributed more lasting value to the project.\n\nJudge substance, not spectacle:\n- Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise.\n- Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one.\n- Do not favor a side merely because its patch is longer or noisier.\n- Weight what the change does for the project, not the contributor's name.\n\nReturn ONLY a JSON object: {\"winner\": \"A\" or \"B\", \"ratio\": \"N:M\", \"explanation\": \"...\"}\nThe explanation must cite concrete differences in the patches (1-3 sentences).\n\nSide A — contributor: tommy-mor\nSide A — commit message:\n[595b3850] Fix star-topology ranking by using degree-based d_max (#146).\n\nA pure forward star at the default `>` ratio (2:1) produced uniform 1/3\nscores, and the alphabetical-fallback sort placed the unambiguous winner\nlast. Root cause: `compute_scores_from_edges` divided by the max sum of\npairwise-normalized weights, so every node ended up with P_ii = 0 — a\nbipartite Markov chain whose power iteration oscillated and, after the\nconfigured even iteration count, returned to the uniform initial state.\n\nSwitch the divisor to the unweighted max neighbor degree, matching the\ncanonical Rank Centrality definition in Negahban–Oh–Shah 2012 §3.1\n(arXiv:1209.1688, eq. defP and the d_max definition in §6). This gives\nevery non-saturated node a positive self-loop, makes the chain aperiodic,\nand converges the star to π_zebra = 1/2, π_alpha = π_beta = 1/4.\n\nAdd Rust regression test and a Clojure test that drives the sorterc\nbinary against four .sorter fixtures (star, inverse star, chain, cycle).\n\nCo-Authored-By: Claude Opus 4.7 (1M context) \n\nSide A — unified diff (full patch):\ndiff --git a/server/src/ranking.rs b/server/src/ranking.rs\nindex 3710c9f64437f5bef3b2121905b6f3bcb7611047..38e6d09b4370e5f8cbae09c0e5760b4e7f1ef7db 100644\n--- a/server/src/ranking.rs\n+++ b/server/src/ranking.rs\n@@ -1,4 +1,4 @@\n-use std::collections::HashMap;\n+use std::collections::{HashMap, HashSet};\n \n use crate::path_types::ItemId;\n use crate::reducer::GroupState;\n@@ -143,23 +143,35 @@ fn compute_scores_from_edges(n: usize, edges: impl Iterator 0 for every non-maximum-degree node, and for max-degree\n+ // nodes whenever any neighbor weight is below 1 (i.e. not a unanimous\n+ // loss). Without this, regular comparison graphs (e.g. a pure star at\n+ // ratio 2:1) produce a bipartite chain that oscillates instead of\n+ // converging — see issue #146.\n let mut out_edges: Vec> = vec![Vec::new(); n];\n- let mut out_deg: Vec = vec![0.0; n];\n+ let mut neighbors: Vec> = vec![HashSet::new(); n];\n \n for ((src, dst), w) in &normalized {\n out_edges[*src].push((*dst, *w));\n- out_deg[*src] += w;\n+ neighbors[*src].insert(*dst);\n+ neighbors[*dst].insert(*src);\n }\n \n- let mut max_out = 0.0f64;\n- for &d in &out_deg {\n- if d > max_out {\n- max_out = d;\n- }\n- }\n- if max_out <= 1e-12 {\n+ let weight_sum: Vec = out_edges\n+ .iter()\n+ .map(|es| es.iter().map(|(_, w)| *w).sum())\n+ .collect();\n+ let d_max = neighbors.iter().map(|s| s.len()).max().unwrap_or(0);\n+ if d_max == 0 {\n return vec![1.0 / n as f64; n];\n }\n+ let d_max_f = d_max as f64;\n \n let mut scores = vec![1.0 / n as f64; n];\n let mut next = vec![0.0f64; n];\n@@ -167,14 +179,14 @@ fn compute_scores_from_edges(n: usize, edges: impl Iterator` ratio (2:1).\n+ /// Under the old (sum-of-weights) divisor every node had P_ii = 0 and the\n+ /// chain was bipartite; power iteration oscillated and returned the\n+ /// uniform initial distribution after an even number of steps. Using the\n+ /// paper's degree-based d_max gives every node a positive self-loop and\n+ /// the chain converges to the correct stationary distribution.\n+ #[test]\n+ fn star_topology_winner_at_top_via_subset() {\n+ let mut g = mk_group();\n+ g.apply_vote(vote(1, \"zebra\", \"alpha\", 2, 1));\n+ g.apply_vote(vote(2, \"zebra\", \"beta\", 2, 1));\n+\n+ let mut items: Vec<(usize, String)> = g\n+ .idx_to_item\n+ .iter()\n+ .enumerate()\n+ .map(|(i, it)| (i, it.as_str().to_string()))\n+ .collect();\n+ items.sort_by(|a, b| a.1.cmp(&b.1));\n+ let idxs: Vec = items.iter().map(|(i, _)| *i).collect();\n+\n+ let ranked = ranked_items_subset(&g, &idxs, 10000, 1e-8);\n+ for r in &ranked {\n+ eprintln!(\"{}: {}\", r.item.as_str(), r.score);\n+ }\n+ assert_eq!(\n+ ranked[0].item.as_str(),\n+ \"https://slug.social/zebra\",\n+ \"zebra won both votes and should rank #1\"\n+ );\n+ }\n+\n #[test]\n fn group_ranking_cache_dirty_flow() {\n let mut g = mk_group();\ndiff --git a/test/fixtures/ranking/chain.sorter b/test/fixtures/ranking/chain.sorter\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..912a96bdc08f631be27f3c9afc7e05004a2457c0\n--- /dev/null\n+++ b/test/fixtures/ranking/chain.sorter\n@@ -0,0 +1,10 @@\n+#t3\n+\n+~/t3/a { head of chain }\n+~/t3/b { middle }\n+~/t3/c { tail }\n+\n+{ a > b }\n+~/t3/a > ~/t3/b\n+{ b > c }\n+~/t3/b > ~/t3/c\ndiff --git a/test/fixtures/ranking/cycle.sorter b/test/fixtures/ranking/cycle.sorter\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..771731ae176e5d77e00ab89767ff2d7465bb7c6b\n--- /dev/null\n+++ b/test/fixtures/ranking/cycle.sorter\n@@ -0,0 +1,12 @@\n+#t4\n+\n+~/t4/a { node a }\n+~/t4/b { node b }\n+~/t4/c { node c }\n+\n+{ a > b }\n+~/t4/a > ~/t4/b\n+{ b > c }\n+~/t4/b > ~/t4/c\n+{ c > a }\n+~/t4/c > ~/t4/a\ndiff --git a/test/fixtures/ranking/star.sorter b/test/fixtures/ranking/star.sorter\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..135c9f9097d57b73c7ab18fac737ed3598d76fbe\n--- /dev/null\n+++ b/test/fixtures/ranking/star.sorter\n@@ -0,0 +1,11 @@\n+#repro\n+\n+~/repro/zebra { winner — beats both others }\n+~/repro/alpha { loser — alphabetically first }\n+~/repro/beta { loser — alphabetically middle }\n+\n+{ zebra beats alpha }\n+~/repro/zebra > ~/repro/alpha\n+\n+{ zebra beats beta }\n+~/repro/zebra > ~/repro/beta\ndiff --git a/test/fixtures/ranking/star_inverse.sorter b/test/fixtures/ranking/star_inverse.sorter\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..dab842fa924e5124865ee216b9565f6c7471c812\n--- /dev/null\n+++ b/test/fixtures/ranking/star_inverse.sorter\n@@ -0,0 +1,11 @@\n+#t2\n+\n+~/t2/win { source of incoming edges (loses both) }\n+~/t2/loss-a { winner }\n+~/t2/loss-b { winner }\n+\n+{ loss-a beats win }\n+~/t2/loss-a > ~/t2/win\n+\n+{ loss-b beats win }\n+~/t2/loss-b > ~/t2/win\ndiff --git a/test/ranking.clj b/test/ranking.clj\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..e1358783a84a264ee633bd79151ba29750b717cf\n--- /dev/null\n+++ b/test/ranking.clj\n@@ -0,0 +1,74 @@\n+(ns test.ranking\n+ \"Drives sorterc on .sorter fixtures and asserts ranking properties.\n+\n+ Regression coverage for issue #146 — pure forward star at default ratio\n+ (2:1 for `>`) used to produce tied uniform scores because the random walk\n+ on the normalized edge weights was bipartite. Fixed by switching to the\n+ degree-based d_max from Negahban–Oh–Shah rank centrality (§3.1).\"\n+ (:require [clojure.test :refer [deftest is testing]]\n+ [babashka.process :as p]\n+ [cheshire.core :as json]\n+ [clojure.java.io :as io]))\n+\n+(def sorterc-bin\n+ \"Path to the locally-built sorterc binary. Builds on demand if missing.\"\n+ (let [dbg \"target/debug/sorterc\"\n+ release \"target/release/sorterc\"]\n+ (cond\n+ (.exists (io/file release)) release\n+ (.exists (io/file dbg)) dbg\n+ :else\n+ (do (println \"building sorterc…\")\n+ (let [r (p/shell {:out :string :err :string :continue true}\n+ \"cargo build -p sorterc\")]\n+ (when-not (zero? (:exit r))\n+ (throw (ex-info \"cargo build -p sorterc failed\"\n+ {:stderr (:err r)}))))\n+ dbg))))\n+\n+(defn compile-sorter [fixture-path]\n+ (let [{:keys [out exit]} (p/shell {:out :string :err :string :continue true}\n+ sorterc-bin \"compile\" fixture-path)]\n+ (when-not (zero? exit)\n+ (throw (ex-info \"sorterc exit nonzero\" {:fixture fixture-path :out out})))\n+ (json/parse-string out true)))\n+\n+(defn first-component-ranking [result]\n+ (-> result :rankings first :components first :ranking))\n+\n+(defn item-leaf [item]\n+ (last (clojure.string/split item #\"/\")))\n+\n+(deftest chain-ranks-head-first\n+ (let [ranking (first-component-ranking (compile-sorter \"test/fixtures/ranking/chain.sorter\"))\n+ names (mapv (comp item-leaf :item) ranking)]\n+ (is (= [\"a\" \"b\" \"c\"] names)\n+ \"chain a>b>c should rank a, b, c in order\")\n+ (is (apply > (map :score ranking))\n+ \"scores should attenuate strictly down the chain\")))\n+\n+(deftest inverse-star-puts-winners-on-top\n+ (let [ranking (first-component-ranking (compile-sorter \"test/fixtures/ranking/star_inverse.sorter\"))\n+ names (mapv (comp item-leaf :item) ranking)]\n+ (is (= \"win\" (last names))\n+ \"the item that lost to both others should be ranked last\")))\n+\n+(deftest cycle-produces-uniform-scores\n+ (let [ranking (first-component-ranking (compile-sorter \"test/fixtures/ranking/cycle.sorter\"))\n+ scores (map :score ranking)]\n+ (is (every? #(< (Math/abs (- % 1/3)) 1e-3) scores)\n+ \"a perfectly symmetric 3-cycle should give every node ~1/3\")))\n+\n+(deftest star-topology-winner-at-top\n+ ;; Issue #146 regression: source-only star at default `>` ratio (2:1).\n+ ;; Pre-fix produced uniform 1/3 scores; alphabetical fallback put the\n+ ;; unambiguous winner at the bottom. Post-fix the chain is aperiodic and\n+ ;; converges to π_zebra = 1/2, π_alpha = π_beta = 1/4.\n+ (let [ranking (first-component-ranking (compile-sorter \"test/fixtures/ranking/star.sorter\"))\n+ names (mapv (comp item-leaf :item) ranking)\n+ by-name (into {} (map (juxt (comp item-leaf :item) :score) ranking))]\n+ (is (= \"zebra\" (first names))\n+ \"zebra won both votes and should rank #1\")\n+ (is (< (Math/abs (- (by-name \"zebra\") 0.5)) 1e-3))\n+ (is (< (Math/abs (- (by-name \"alpha\") 0.25)) 1e-3))\n+ (is (< (Math/abs (- (by-name \"beta\") 0.25)) 1e-3))))\n\n\nSide B — contributor: tommy-mor\nSide B — commit message:\n[af73743d] Replace GroupState with ScopeVotes and derive edges at ranking time.\n\nStore only uuid_votes and recent_votes per scope; rank centrality and pair logic rebuild edge weights on demand instead of maintaining cached state.\n\nCo-authored-by: Cursor \n\nSide B — unified diff (full patch):\ndiff --git a/server/src/events.rs b/server/src/events.rs\nindex 8a166d49b4f26835fbc2b58cb1f4bdbf002763b8..015208311f6c5c23a0e8aab068d002a69c89c4e1 100644\n--- a/server/src/events.rs\n+++ b/server/src/events.rs\n@@ -43,7 +43,7 @@ pub enum ViewEvent {\n #[derive(Debug, Clone, Serialize, Deserialize)]\n #[serde(tag = \"type\", rename_all = \"snake_case\")]\n pub enum Event {\n- /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::GroupState`] on boot).\n+ /// Pairwise comparison vote (replayed into the parent node's [`crate::reducer::ScopeVotes`] on boot).\n /// `scope` is the parent [`crate::path_types::ItemId`] string; empty string is the tree root.\n VoteRecorded {\n ts: i64,\ndiff --git a/server/src/html/mod.rs b/server/src/html/mod.rs\nindex 4eff2e19ed4d303ff8e80c1eabd8a15b4990e643..1e2e7a06856d8a62378741aaf5ed94a4ffed337e 100644\n--- a/server/src/html/mod.rs\n+++ b/server/src/html/mod.rs\n@@ -13,7 +13,7 @@ use crate::{\n form_template::template_json_compact,\n path_types::ItemId,\n ranking::{\n- connected_components_from_voted_pairs, ranked_items_subset, RankedItem, MAX_ITERS, TOL,\n+ ranked_items_subset, scope_components, RankedItem, MAX_ITERS, TOL,\n },\n reducer::{GlobalTree, NodeState},\n state::AppState,\n@@ -397,10 +397,9 @@ pub fn ranking_panel_with_highlights(\n tree: &GlobalTree,\n highlighted: &HashSet,\n ) -> Markup {\n- let group = &node.local_ranking;\n- let n = group.idx_to_item.len();\n- let (comps, _isolates) =\n- connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());\n+ let scope = &node.votes;\n+ let (comps, _isolates, _) =\n+ scope_components(scope);\n \n // Each connected component of voted items is its own ranking; isolated and\n // never-voted children fall into the \"unranked\" bucket below.\n@@ -410,7 +409,7 @@ pub fn ranking_panel_with_highlights(\n if comp.len() < 2 {\n continue;\n }\n- let ranked = ranked_items_subset(group, comp, MAX_ITERS, TOL);\n+ let ranked = ranked_items_subset(scope, comp, MAX_ITERS, TOL);\n for r in &ranked {\n ranked_ids.insert(r.item.clone());\n }\ndiff --git a/server/src/html/vote.rs b/server/src/html/vote.rs\nindex bf82aef3ad9c5f4e9e877c47dab27beb29a80b8f..3aa00c417c89a9cab3417c650b50ed7c73f08e20 100644\n--- a/server/src/html/vote.rs\n+++ b/server/src/html/vote.rs\n@@ -14,7 +14,7 @@ use crate::{\n html::{ranking_panel_with_highlights, scope_theme_style, JsBuilder},\n pair::{children_of, resolve_pair, suggest_next_pair_in_pool},\n path_types::ItemId,\n- reducer::{GlobalTree, GroupState, NodeState, VoteData},\n+ reducer::{GlobalTree, NodeState, ScopeVotes, VoteData},\n state::{parse_item_param, AppState},\n ui_action::UI_RPC_FIELD,\n };\n@@ -68,8 +68,8 @@ fn ratios_for_page(v: &VoteData, page_left: &ItemId, page_right: &ItemId) -> (i3\n }\n }\n \n-fn edge_votes(group: &GroupState, left: &ItemId, right: &ItemId) -> Vec {\n- group\n+fn edge_votes(scope: &ScopeVotes, left: &ItemId, right: &ItemId) -> Vec {\n+ scope\n .recent_votes\n .iter()\n .filter(|v| {\n@@ -113,11 +113,11 @@ fn slider_value_from_ratios(r_left: i32, r_right: i32) -> i32 {\n \n fn vote_edge_history(\n tree: &GlobalTree,\n- group: &GroupState,\n+ scope: &ScopeVotes,\n left: &ItemId,\n right: &ItemId,\n ) -> Markup {\n- let mut votes = edge_votes(group, left, right);\n+ let mut votes = edge_votes(scope, left, right);\n votes.sort_by(|a, b| b.ts.cmp(&a.ts));\n let legend_left = child_title(tree, left);\n let legend_right = child_title(tree, right);\n@@ -228,9 +228,9 @@ pub(crate) fn vote_recorded_morph(\n ) -> JsBuilder {\n let pool = children_of(tree, parent);\n let empty = NodeState::default();\n- let group = tree.get(parent).unwrap_or(&empty).local_ranking.clone();\n- let edge_history = vote_edge_history(tree, &group, left, right);\n- let next_pair = suggest_next(&group, left, right, &pool);\n+ let scope = tree.get(parent).unwrap_or(&empty).votes.clone();\n+ let edge_history = vote_edge_history(tree, &scope, left, right);\n+ let next_pair = suggest_next(&scope, left, right, &pool);\n let actions = vote_compare_actions(parent, next_pair.as_ref());\n let sidebar = vote_ranking_sidebar(tree, parent, left, right);\n JsBuilder::new()\n@@ -252,12 +252,12 @@ fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) ->\n }\n \n fn suggest_next(\n- group: &GroupState,\n+ scope: &ScopeVotes,\n left: &ItemId,\n right: &ItemId,\n pool: &[ItemId],\n ) -> Option<(ItemId, ItemId)> {\n- suggest_next_pair_in_pool(group, pool, Some((left, right)))\n+ suggest_next_pair_in_pool(scope, pool, Some((left, right)))\n }\n \n pub async fn vote_page(\n@@ -284,9 +284,9 @@ pub async fn vote_page(\n };\n \n let pool = children_of(&tree, &parent);\n- let group = &parent_node.local_ranking;\n- let next_pair = suggest_next(group, &left, &right, &pool);\n- let edge_history = vote_edge_history(&tree, group, &left, &right);\n+ let scope = &parent_node.votes;\n+ let next_pair = suggest_next(&scope, &left, &right, &pool);\n+ let edge_history = vote_edge_history(&tree, &scope, &left, &right);\n \n let rpc_json = template_json_compact(&serde_json::json!({\n \"action\": \"record_vote\",\n@@ -388,8 +388,8 @@ mod polarity_tests {\n let mut tree = GlobalTree::new();\n tree.apply_vote(&parent, vote, TEST_ACTOR_UUID);\n \n- let group = &tree.get(&parent).unwrap().local_ranking;\n- let ranked = ranked_items(group);\n+ let scope = &tree.get(&parent).unwrap().votes;\n+ let ranked = ranked_items(scope);\n assert_eq!(\n ranked[0].item, left,\n \"left item should rank first when ratio favours the left\"\ndiff --git a/server/src/pair.rs b/server/src/pair.rs\nindex 42a1b1eb2adf16730d34d0fe23c13d5a75d7ba27..9873295c51526726089875bbfd2f97d7faa91872 100644\n--- a/server/src/pair.rs\n+++ b/server/src/pair.rs\n@@ -11,8 +11,8 @@ use std::collections::{HashMap, HashSet};\n \n use crate::{\n path_types::ItemId,\n- ranking::{connected_components_from_voted_pairs, ranked_items},\n- reducer::{GlobalTree, GroupState},\n+ ranking::{pair_is_voted, ranked_items, scope_components},\n+ reducer::{GlobalTree, ScopeVotes},\n };\n \n fn pairs_match(a: &ItemId, b: &ItemId, x: &ItemId, y: &ItemId) -> bool {\n@@ -23,26 +23,15 @@ fn pair_excluded(a: &ItemId, b: &ItemId, exclude: Option<(&ItemId, &ItemId)>) ->\n exclude.is_some_and(|(x, y)| pairs_match(a, b, x, y))\n }\n \n-fn pair_is_voted(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {\n- let Some(&ai) = group.item_to_idx.get(a) else {\n- return false;\n- };\n- let Some(&bi) = group.item_to_idx.get(b) else {\n- return false;\n- };\n- let (i, j) = if ai < bi { (ai, bi) } else { (bi, ai) };\n- group.voted_pairs.contains(&(i, j))\n-}\n \n struct ComponentLayout {\n ids: HashMap,\n established: HashSet,\n }\n \n-fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {\n- let n = group.idx_to_item.len();\n- let (comps, isolates) =\n- connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());\n+fn component_layout(scope: &ScopeVotes, pool: &[ItemId]) -> ComponentLayout {\n+ let (comps, isolates, idx_to_item) = scope_components(scope);\n+ let n = idx_to_item.len();\n \n let mut established = HashSet::new();\n let mut ids: HashMap = HashMap::new();\n@@ -52,14 +41,14 @@ fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {\n }\n for &idx in comp {\n if idx < n {\n- ids.insert(group.idx_to_item[idx].clone(), comp_idx);\n+ ids.insert(idx_to_item[idx].clone(), comp_idx);\n }\n }\n }\n let mut next = comps.len();\n for &idx in &isolates {\n if idx < n {\n- ids.insert(group.idx_to_item[idx].clone(), next);\n+ ids.insert(idx_to_item[idx].clone(), next);\n next += 1;\n }\n }\n@@ -121,7 +110,7 @@ fn established_groups_in_pool<'a>(\n groups\n }\n \n-fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec {\n+fn ranked_pool_order(group: &ScopeVotes, pool: &[ItemId]) -> Vec {\n let pool_set: HashSet<_> = pool.iter().collect();\n ranked_items(group)\n .into_iter()\n@@ -132,7 +121,7 @@ fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec {\n \n /// Walk 1↔2, 2↔3, …; optional `require_unvoted` skips voted edges.\n fn zip_adjacent_pair(\n- group: &GroupState,\n+ group: &ScopeVotes,\n order: &[ItemId],\n exclude: Option<(&ItemId, &ItemId)>,\n require_unvoted: bool,\n@@ -153,7 +142,7 @@ fn zip_adjacent_pair(\n \n /// Grow the voted graph toward one component (no rank centrality).\n fn suggest_grow_pair(\n- group: &GroupState,\n+ group: &ScopeVotes,\n pool: &[ItemId],\n layout: &ComponentLayout,\n exclude: Option<(&ItemId, &ItemId)>,\n@@ -216,7 +205,7 @@ fn suggest_grow_pair(\n \n /// Pick the next pair to vote on within `pool`.\n pub fn suggest_next_pair_in_pool(\n- group: &GroupState,\n+ group: &ScopeVotes,\n pool: &[ItemId],\n exclude: Option<(&ItemId, &ItemId)>,\n ) -> Option<(ItemId, ItemId)> {\n@@ -315,7 +304,7 @@ pub fn resolve_pair(\n (None, None) => {\n let group = tree\n .get(parent)\n- .map(|n| &n.local_ranking)\n+ .map(|n| &n.votes)\n .cloned()\n .unwrap_or_default();\n suggest_next_pair_in_pool(&group, &children, None).ok_or(PairError::NoPair)\n@@ -398,7 +387,7 @@ mod tests {\n \"https://reddit.com/r/rust/b\",\n ],\n );\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n assert!(!pair_is_voted(&group, &pool[0], &pool[1]));\n assert!(suggest_next_pair_in_pool(&group, &pool, None).is_some());\n@@ -417,7 +406,7 @@ mod tests {\n );\n let vote = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, vote);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let (l, r) = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let voted_ab = (l.as_str() == \"https://reddit.com/r/rust/a\" && r.as_str() == \"https://reddit.com/r/rust/b\")\n@@ -441,7 +430,7 @@ mod tests {\n let cd = test_vote(2, \"https://reddit.com/r/rust/c\", \"https://reddit.com/r/rust/d\", 2, 1);\n apply(&mut tree, &parent, ab);\n apply(&mut tree, &parent, cd);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -467,7 +456,7 @@ mod tests {\n );\n let ab = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, ab);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -496,7 +485,7 @@ mod tests {\n );\n let ab = test_vote(1, \"https://reddit.com/r/rust/a\", \"https://reddit.com/r/rust/b\", 2, 1);\n apply(&mut tree, &parent, ab);\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -522,7 +511,7 @@ mod tests {\n let v = test_vote(1, a, b, l, r);\n apply(&mut tree, &parent, v);\n }\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\n@@ -550,7 +539,7 @@ mod tests {\n let v = test_vote(1, a, b, l, r);\n apply(&mut tree, &parent, v);\n }\n- let group = tree.get(&parent).unwrap().local_ranking.clone();\n+ let group = tree.get(&parent).unwrap().votes.clone();\n let pool = children_of(&tree, &parent);\n let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();\n let chosen = pair_set(&pair);\ndiff --git a/server/src/projection_store.rs b/server/src/projection_store.rs\nindex 27fc0bb0519d9f035dceec1fc8b0fa74b00b6b40..8c1a466183a96173fe52b144fb67c2454b715fbd 100644\n--- a/server/src/projection_store.rs\n+++ b/server/src/projection_store.rs\n@@ -214,7 +214,7 @@ mod tests {\n \n let loaded = store.load_tree().unwrap();\n let root = loaded.get(&ItemId::root()).unwrap();\n- assert_eq!(root.local_ranking.idx_to_item.len(), 2);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 2);\n assert!(root.children.contains(&ItemId::opaque(\"alpha\")));\n }\n \ndiff --git a/server/src/ranking.rs b/server/src/ranking.rs\nindex 1fc3298d2b2864e9711cd262a034677e45c7090c..cc4de6da11b02135e5e6b1d2a68646cb77870b9d 100644\n--- a/server/src/ranking.rs\n+++ b/server/src/ranking.rs\n@@ -1,7 +1,7 @@\n-use std::collections::{HashMap, HashSet};\n+use std::collections::{BTreeSet, HashMap, HashSet};\n \n use crate::path_types::ItemId;\n-use crate::reducer::GroupState;\n+use crate::reducer::{canonical_pair_ids, ScopeVotes};\n \n #[derive(Debug, Clone)]\n pub struct RankedItem {\n@@ -9,15 +9,76 @@ pub struct RankedItem {\n pub score: f64,\n }\n \n-/// Power-iteration cap and convergence tolerance for rank centrality.\n pub const MAX_ITERS: usize = 10_000;\n pub const TOL: f64 = 1e-8;\n \n-/// Compute connected components over the voted-pairs graph (treated as undirected).\n-///\n-/// Returns:\n-/// - `components`: each component is a sorted list of node indices, excluding isolates.\n-/// - `isolates`: sorted list of node indices with degree 0 (no voted pairs).\n+pub fn item_index(scope: &ScopeVotes) -> (HashMap, Vec) {\n+ let mut item_strs: BTreeSet = BTreeSet::new();\n+ for vote in scope.uuid_votes.values() {\n+ item_strs.insert(vote.a.as_str().to_string());\n+ item_strs.insert(vote.b.as_str().to_string());\n+ }\n+ let mut idx_to_item: Vec = Vec::with_capacity(item_strs.len());\n+ let mut item_to_idx: HashMap = HashMap::with_capacity(item_strs.len());\n+ for s in item_strs {\n+ let id = ItemId::from_storage(&s).unwrap_or_else(|| ItemId::opaque(&s));\n+ let idx = idx_to_item.len();\n+ item_to_idx.insert(id.clone(), idx);\n+ idx_to_item.push(id);\n+ }\n+ (item_to_idx, idx_to_item)\n+}\n+\n+pub fn edges_from_scope(scope: &ScopeVotes) -> HashMap<(usize, usize), f64> {\n+ let (item_to_idx, _) = item_index(scope);\n+ let mut edges: HashMap<(usize, usize), f64> = HashMap::new();\n+ for vote in scope.uuid_votes.values() {\n+ let Some(&ai) = item_to_idx.get(&vote.a) else {\n+ continue;\n+ };\n+ let Some(&bi) = item_to_idx.get(&vote.b) else {\n+ continue;\n+ };\n+ let w_a = vote.ratio_left as f64 * vote.trust_weight;\n+ let w_b = vote.ratio_right as f64 * vote.trust_weight;\n+ if w_a > 0.0 {\n+ *edges.entry((bi, ai)).or_insert(0.0) += w_a;\n+ }\n+ if w_b > 0.0 {\n+ *edges.entry((ai, bi)).or_insert(0.0) += w_b;\n+ }\n+ }\n+ edges\n+}\n+\n+pub fn edge_weight_sum(scope: &ScopeVotes) -> f64 {\n+ edges_from_scope(scope).values().sum()\n+}\n+\n+pub fn voted_pair_indices(scope: &ScopeVotes) -> HashSet<(usize, usize)> {\n+ let (item_to_idx, _) = item_index(scope);\n+ let mut pairs = HashSet::new();\n+ for vote in scope.uuid_votes.values() {\n+ let Some(&ai) = item_to_idx.get(&vote.a) else {\n+ continue;\n+ };\n+ let Some(&bi) = item_to_idx.get(&vote.b) else {\n+ continue;\n+ };\n+ let (i, j) = if ai < bi { (ai, bi) } else { (bi, ai) };\n+ pairs.insert((i, j));\n+ }\n+ pairs\n+}\n+\n+pub fn pair_is_voted(scope: &ScopeVotes, a: &ItemId, b: &ItemId) -> bool {\n+ let (lo, hi) = canonical_pair_ids(a, b);\n+ scope\n+ .uuid_votes\n+ .keys()\n+ .any(|(_, l, h)| l == &lo && h == &hi)\n+}\n+\n pub fn connected_components_from_voted_pairs(\n n: usize,\n voted_pairs: impl Iterator,\n@@ -63,20 +124,25 @@ pub fn connected_components_from_voted_pairs(\n (comps, isolates)\n }\n \n-/// Compute rank-centrality scores for the whole group and return items sorted\n-/// by score (descending). Recomputed fresh from the edge set on every call —\n-/// there is no score cache.\n-pub fn ranked_items(group: &GroupState) -> Vec {\n- let n = group.idx_to_item.len();\n- let scores =\n- compute_scores_from_edges(n, group.edges.iter().map(|(&k, &w)| (k, w)), MAX_ITERS, TOL);\n+pub fn scope_components(scope: &ScopeVotes) -> (Vec>, Vec, Vec) {\n+ let (_, idx_to_item) = item_index(scope);\n+ let n = idx_to_item.len();\n+ let pairs = voted_pair_indices(scope);\n+ let (comps, isolates) = connected_components_from_voted_pairs(n, pairs.into_iter());\n+ (comps, isolates, idx_to_item)\n+}\n \n- let mut items: Vec = group\n- .idx_to_item\n- .iter()\n+pub fn ranked_items(scope: &ScopeVotes) -> Vec {\n+ let (_, idx_to_item) = item_index(scope);\n+ let n = idx_to_item.len();\n+ let edges = edges_from_scope(scope);\n+ let scores = compute_scores_from_edges(n, edges.into_iter(), MAX_ITERS, TOL);\n+\n+ let mut items: Vec = idx_to_item\n+ .into_iter()\n .enumerate()\n .map(|(i, item)| RankedItem {\n- item: item.clone(),\n+ item,\n score: *scores.get(i).unwrap_or(&0.0),\n })\n .collect();\n@@ -89,11 +155,8 @@ pub fn ranked_items(group: &GroupState) -> Vec {\n items\n }\n \n-/// Highest- and lowest-ranked items for a group. Returns up to `k` items from\n-/// each end with no overlap. If the group has `2*k` items or fewer, `top` holds\n-/// the full ranking and `bottom` is empty (so nothing is shown twice).\n-pub fn top_bottom(group: &GroupState, k: usize) -> (Vec, Vec) {\n- let items = ranked_items(group);\n+pub fn top_bottom(scope: &ScopeVotes, k: usize) -> (Vec, Vec) {\n+ let items = ranked_items(scope);\n if k == 0 || items.len() <= 2 * k {\n return (items, Vec::new());\n }\n@@ -115,7 +178,6 @@ pub fn compute_scores_from_edges(\n return vec![1.0];\n }\n \n- // Collect raw edges into a map for pairwise normalization.\n let mut raw: HashMap<(usize, usize), f64> = HashMap::new();\n for ((src, dst), w) in edges {\n if src >= n || dst >= n || w <= 0.0 {\n@@ -124,9 +186,6 @@ pub fn compute_scores_from_edges(\n *raw.entry((src, dst)).or_insert(0.0) += w;\n }\n \n- // Pairwise normalization: a_ij = A_ij / (A_ij + A_ji).\n- // This ensures repeated votes on the same pair don't inflate influence\n- // beyond what the ratio implies.\n let keys: Vec<(usize, usize)> = raw.keys().copied().collect();\n let mut normalized: HashMap<(usize, usize), f64> = HashMap::new();\n for (i, j) in keys {\n@@ -145,17 +204,6 @@ pub fn compute_scores_from_edges(\n }\n }\n \n- // Rank Centrality (Negahban, Oh, Shah 2012, §3.1):\n- // P_ij = (1/d_max) * A_ij for i ≠ j compared\n- // P_ii = 1 - (1/d_max) * Σ_k A_ik\n- // where d_i is the *degree* (number of distinct neighbors compared) and\n- // d_max = max_i d_i. Using the unweighted degree — not the sum of\n- // pairwise-normalized weights — is what guarantees aperiodicity: it\n- // forces P_ii > 0 for every non-maximum-degree node, and for max-degree\n- // nodes whenever any neighbor weight is below 1 (i.e. not a unanimous\n- // loss). Without this, regular comparison graphs (e.g. a pure star at\n- // ratio 2:1) produce a bipartite chain that oscillates instead of\n- // converging — see issue #146.\n let mut out_edges: Vec> = vec![Vec::new(); n];\n let mut neighbors: Vec> = vec![HashSet::new(); n];\n \n@@ -213,11 +261,8 @@ pub fn compute_scores_from_edges(\n scores\n }\n \n-/// Rank-centrality within a subset of items (an induced subgraph), using the group's aggregated edges.\n-///\n-/// `idxs` are indices into `group.idx_to_item`. The returned items use the original item names.\n pub fn ranked_items_subset(\n- group: &GroupState,\n+ scope: &ScopeVotes,\n idxs: &[usize],\n max_iters: usize,\n tol: f64,\n@@ -226,13 +271,15 @@ pub fn ranked_items_subset(\n return vec![];\n }\n \n- // Map original idx -> compact idx [0..m)\n+ let (_, idx_to_item) = item_index(scope);\n+ let edges = edges_from_scope(scope);\n+\n let mut map: HashMap = HashMap::with_capacity(idxs.len());\n for (j, &i) in idxs.iter().enumerate() {\n map.insert(i, j);\n }\n \n- let edges_iter = group.edges.iter().filter_map(|(&(src, dst), &w)| {\n+ let edges_iter = edges.into_iter().filter_map(|((src, dst), w)| {\n let s = *map.get(&src)?;\n let d = *map.get(&dst)?;\n Some(((s, d), w))\n@@ -240,12 +287,11 @@ pub fn ranked_items_subset(\n \n let scores = compute_scores_from_edges(idxs.len(), edges_iter, max_iters, tol);\n \n- // Filter out entries where idx_to_item doesn't have the slot (shouldn't happen, but be safe).\n let mut items: Vec = idxs\n .iter()\n .enumerate()\n .filter_map(|(j, &orig)| {\n- let item = group.idx_to_item.get(orig)?.clone();\n+ let item = idx_to_item.get(orig)?.clone();\n Some(RankedItem {\n item,\n score: *scores.get(j).unwrap_or(&0.0),\n@@ -261,8 +307,8 @@ pub fn ranked_items_subset(\n items\n }\n \n-pub fn group_summary_scores(group: &GroupState) -> HashMap {\n- ranked_items(group)\n+pub fn group_summary_scores(scope: &ScopeVotes) -> HashMap {\n+ ranked_items(scope)\n .into_iter()\n .map(|r| (r.item, r.score))\n .collect()\n@@ -274,32 +320,26 @@ mod tests {\n use crate::identity::{DEFAULT_PSEUDONYM, TEST_ACTOR_UUID};\n use crate::reducer::VoteData;\n \n- fn mk_group() -> GroupState {\n- GroupState::new()\n+ fn mk_scope() -> ScopeVotes {\n+ ScopeVotes::default()\n }\n \n fn vote(ts: i64, a: &str, b: &str, l: i32, r: i32) -> VoteData {\n VoteData::from_event(ts, a, b, l, r, DEFAULT_PSEUDONYM.to_string(), 1.0).unwrap()\n }\n \n- fn apply(g: &mut GroupState, v: VoteData) {\n- g.apply_vote(v, TEST_ACTOR_UUID);\n+ fn apply(scope: &mut ScopeVotes, v: VoteData) {\n+ scope.apply_vote(v, TEST_ACTOR_UUID);\n }\n \n- /// Regression for issue #146: pure forward star at default `>` ratio (2:1).\n- /// Under the old (sum-of-weights) divisor every node had P_ii = 0 and the\n- /// chain was bipartite; power iteration oscillated and returned the\n- /// uniform initial distribution after an even number of steps. Using the\n- /// paper's degree-based d_max gives every node a positive self-loop and\n- /// the chain converges to the correct stationary distribution.\n #[test]\n fn star_topology_winner_at_top_via_subset() {\n- let mut g = mk_group();\n- g.apply_vote(vote(1, \"zebra\", \"alpha\", 2, 1), TEST_ACTOR_UUID);\n- g.apply_vote(vote(2, \"zebra\", \"beta\", 2, 1), TEST_ACTOR_UUID);\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"zebra\", \"alpha\", 2, 1));\n+ apply(&mut scope, vote(2, \"zebra\", \"beta\", 2, 1));\n \n- let mut items: Vec<(usize, String)> = g\n- .idx_to_item\n+ let (_, idx_to_item) = item_index(&scope);\n+ let mut items: Vec<(usize, String)> = idx_to_item\n .iter()\n .enumerate()\n .map(|(i, it)| (i, it.as_str().to_string()))\n@@ -307,78 +347,51 @@ mod tests {\n items.sort_by(|a, b| a.1.cmp(&b.1));\n let idxs: Vec = items.iter().map(|(i, _)| *i).collect();\n \n- let ranked = ranked_items_subset(&g, &idxs, 10000, 1e-8);\n- for r in &ranked {\n- eprintln!(\"{}: {}\", r.item.as_str(), r.score);\n- }\n- assert_eq!(\n- ranked[0].item.as_str(),\n- \"zebra\",\n- \"zebra won both votes and should rank #1\"\n- );\n+ let ranked = ranked_items_subset(&scope, &idxs, 10000, 1e-8);\n+ assert_eq!(ranked[0].item.as_str(), \"zebra\");\n }\n \n #[test]\n fn top_bottom_splits_ends_without_overlap() {\n- let mut g = mk_group();\n- // Chain a > b > c > d > e > f so ranks are well separated.\n+ let mut scope = mk_scope();\n for (hi, lo) in [(\"a\", \"b\"), (\"b\", \"c\"), (\"c\", \"d\"), (\"d\", \"e\"), (\"e\", \"f\")] {\n- apply(&mut g, vote(1, hi, lo, 2, 1));\n+ apply(&mut scope, vote(1, hi, lo, 2, 1));\n }\n- let (top, bottom) = top_bottom(&g, 2);\n+ let (top, bottom) = top_bottom(&scope, 2);\n assert_eq!(top.len(), 2);\n assert_eq!(bottom.len(), 2);\n- // No overlap between the two ends.\n for t in &top {\n assert!(bottom.iter().all(|b| b.item != t.item));\n }\n- // Best item ranks above the worst item.\n assert!(top[0].score >= bottom[bottom.len() - 1].score);\n }\n \n #[test]\n fn top_bottom_small_group_has_empty_bottom() {\n- let mut g = mk_group();\n- apply(&mut g, vote(1, \"a\", \"b\", 2, 1));\n- let (top, bottom) = top_bottom(&g, 5);\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 2, 1));\n+ let (top, bottom) = top_bottom(&scope, 5);\n assert_eq!(top.len(), 2);\n assert!(bottom.is_empty());\n }\n \n #[test]\n fn connected_components_split_disconnected_pairs() {\n- let mut g = mk_group();\n- // Two disconnected edges: (a,b) and (c,d)\n- apply(&mut g, vote(1, \"a\", \"b\", 3, 1));\n- apply(&mut g, vote(2, \"c\", \"d\", 3, 1));\n-\n- let n = g.idx_to_item.len();\n- let (mut comps, isolates) =\n- connected_components_from_voted_pairs(n, g.voted_pairs.iter().copied());\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 3, 1));\n+ apply(&mut scope, vote(2, \"c\", \"d\", 3, 1));\n+\n+ let (_, idx_to_item) = item_index(&scope);\n+ let (mut comps, isolates, _) = scope_components(&scope);\n assert!(isolates.is_empty());\n- // Order-independent: sort components by their item names for stable assert.\n comps.sort_by_key(|c| {\n c.iter()\n- .map(|&i| g.idx_to_item[i].clone())\n+ .map(|&i| idx_to_item[i].clone())\n .collect::>()\n });\n assert_eq!(comps.len(), 2);\n- let comp0 = comps[0]\n- .iter()\n- .map(|&i| g.idx_to_item[i].as_str())\n- .collect::>();\n- let comp1 = comps[1]\n- .iter()\n- .map(|&i| g.idx_to_item[i].as_str())\n- .collect::>();\n- assert_eq!(comp0, vec![\"a\", \"b\"]);\n- assert_eq!(comp1, vec![\"c\", \"d\"]);\n }\n \n- /// A random spanning tree over 26 items needs only n−1 = 25 pairwise votes.\n- /// When each vote uses the \"perfect\" ratio (strength left : strength right =\n- /// (idx_left+1) : (idx_right+1)), rank centrality recovers the true order.\n- /// See `rank-eric.py` (Eric's demo of Negahban–Oh–Shah rank centrality).\n #[test]\n fn twenty_five_random_votes_perfect_ratios_sort_alphabet() {\n use rand::seq::SliceRandom;\n@@ -390,13 +403,13 @@ mod tests {\n let mut perm: Vec = (0..N).collect();\n perm.shuffle(&mut rng);\n \n- let mut g = mk_group();\n+ let mut scope = mk_scope();\n for k in 1..N {\n let i = *perm[..k].choose(&mut rng).unwrap();\n let j = perm[k];\n let (a, b) = (letters[i], letters[j]);\n apply(\n- &mut g,\n+ &mut scope,\n vote(\n k as i64,\n &a.to_string(),\n@@ -407,34 +420,25 @@ mod tests {\n );\n }\n \n- let ranked = ranked_items(&g);\n+ let ranked = ranked_items(&scope);\n assert_eq!(ranked.len(), N);\n for (rank, item) in ranked.iter().enumerate() {\n let expected = char::from(b'a' + (N - 1 - rank) as u8);\n- assert_eq!(\n- item.item.as_str(),\n- expected.to_string(),\n- \"rank {rank}: expected '{expected}', got '{}'\",\n- item.item.as_str()\n- );\n+ assert_eq!(item.item.as_str(), expected.to_string());\n }\n }\n \n #[test]\n fn subset_ranking_ranks_within_component_only() {\n- let mut g = mk_group();\n- apply(&mut g, vote(1, \"a\", \"b\", 3, 1)); // a > b\n- apply(&mut g, vote(2, \"c\", \"d\", 1, 4)); // d > c\n-\n- let (comps, _) = connected_components_from_voted_pairs(\n- g.idx_to_item.len(),\n- g.voted_pairs.iter().copied(),\n- );\n+ let mut scope = mk_scope();\n+ apply(&mut scope, vote(1, \"a\", \"b\", 3, 1));\n+ apply(&mut scope, vote(2, \"c\", \"d\", 1, 4));\n+\n+ let (comps, _, _) = scope_components(&scope);\n assert_eq!(comps.len(), 2);\n \n- // Rank each component and ensure winner is first within that component.\n for comp in comps {\n- let ranked = ranked_items_subset(&g, &comp, 10000, 1e-8);\n+ let ranked = ranked_items_subset(&scope, &comp, 10000, 1e-8);\n assert_eq!(ranked.len(), 2);\n let names = ranked.iter().map(|r| r.item.as_str()).collect::>();\n if names.contains(&\"a\") {\ndiff --git a/server/src/reducer.rs b/server/src/reducer.rs\nindex 8c4c9f83635cbcbb037d680dbae2aa99cb2dc785..e6d8c8d2fe763f4928cfbd7c300c8d9768968a3f 100644\n--- a/server/src/reducer.rs\n+++ b/server/src/reducer.rs\n@@ -4,6 +4,24 @@ use serde::{Deserialize, Serialize};\n \n use crate::path_types::ItemId;\n \n+/// `(actor_uuid, min_item_id, max_item_id)` — one vote slot per human per pair.\n+pub type UuidVoteKey = (String, String, String);\n+\n+pub fn canonical_pair_ids(a: &ItemId, b: &ItemId) -> (String, String) {\n+ let ak = a.as_str().to_string();\n+ let bk = b.as_str().to_string();\n+ if ak <= bk {\n+ (ak, bk)\n+ } else {\n+ (bk, ak)\n+ }\n+}\n+\n+pub fn uuid_vote_key(actor_uuid: &str, a: &ItemId, b: &ItemId) -> UuidVoteKey {\n+ let (lo, hi) = canonical_pair_ids(a, b);\n+ (actor_uuid.to_string(), lo, hi)\n+}\n+\n /// Parsed pairwise vote (internal representation).\n #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]\n pub struct VoteData {\n@@ -44,118 +62,20 @@ impl VoteData {\n }\n }\n \n+/// Votes cast within one ranking scope (parent node). Edges and rankings are\n+/// derived on demand from [`Self::uuid_votes`].\n #[derive(Debug, Clone, Default, Serialize, Deserialize)]\n-pub struct GroupState {\n- pub item_to_idx: HashMap,\n- pub idx_to_item: Vec,\n- pub edges: HashMap<(usize, usize), f64>,\n- pub voted_pairs: HashSet<(usize, usize)>,\n- /// Latest vote per `(actor_uuid, min_idx, max_idx)` — Sybil dedup anchor.\n- pub uuid_votes: HashMap<(String, usize, usize), VoteData>,\n+pub struct ScopeVotes {\n+ pub uuid_votes: HashMap,\n pub recent_votes: Vec,\n }\n \n-impl GroupState {\n- pub fn new() -> Self {\n- Self {\n- item_to_idx: HashMap::new(),\n- idx_to_item: Vec::new(),\n- edges: HashMap::new(),\n- voted_pairs: HashSet::new(),\n- uuid_votes: HashMap::new(),\n- recent_votes: Vec::new(),\n- }\n- }\n-\n- fn ensure_item(&mut self, item: &ItemId) -> usize {\n- if let Some(&idx) = self.item_to_idx.get(item) {\n- return idx;\n- }\n- let idx = self.idx_to_item.len();\n- self.idx_to_item.push(item.clone());\n- self.item_to_idx.insert(item.clone(), idx);\n- idx\n- }\n-\n- fn add_edge_weight(&mut self, src: usize, dst: usize, w: f64) {\n- if w <= 0.0 {\n- return;\n- }\n- *self.edges.entry((src, dst)).or_insert(0.0) += w;\n- }\n-\n- fn subtract_edge_weight(&mut self, src: usize, dst: usize, w: f64) {\n- if w <= 0.0 {\n- return;\n- }\n- if let Some(entry) = self.edges.get_mut(&(src, dst)) {\n- *entry -= w;\n- if *entry <= 0.0 {\n- self.edges.remove(&(src, dst));\n- }\n- }\n- }\n-\n- fn apply_weights(&mut self, vote: &VoteData, a_idx: usize, b_idx: usize) {\n- let w_a = vote.ratio_left as f64 * vote.trust_weight;\n- let w_b = vote.ratio_right as f64 * vote.trust_weight;\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n- self.voted_pairs.insert((i, j));\n- self.add_edge_weight(b_idx, a_idx, w_a);\n- self.add_edge_weight(a_idx, b_idx, w_b);\n- }\n-\n- fn rollback_weights(&mut self, vote: &VoteData) {\n- let a_idx = match self.item_to_idx.get(&vote.a) {\n- Some(&i) => i,\n- None => return,\n- };\n- let b_idx = match self.item_to_idx.get(&vote.b) {\n- Some(&i) => i,\n- None => return,\n- };\n- let w_a = vote.ratio_left as f64 * vote.trust_weight;\n- let w_b = vote.ratio_right as f64 * vote.trust_weight;\n- self.subtract_edge_weight(b_idx, a_idx, w_a);\n- self.subtract_edge_weight(a_idx, b_idx, w_b);\n- }\n-\n- /// Apply a validated vote, deduplicating by `actor_uuid` per unordered pair.\n+impl ScopeVotes {\n pub fn apply_vote(&mut self, vote: VoteData, actor_uuid: &str) {\n- let a_idx = self.ensure_item(&vote.a);\n- let b_idx = self.ensure_item(&vote.b);\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n-\n- let dedupe_key = (actor_uuid.to_string(), i, j);\n- if let Some(old) = self.uuid_votes.get(&dedupe_key).cloned() {\n- self.rollback_weights(&old);\n- }\n-\n- self.apply_weights(&vote, a_idx, b_idx);\n- self.uuid_votes.insert(dedupe_key, vote.clone());\n+ let key = uuid_vote_key(actor_uuid, &vote.a, &vote.b);\n+ self.uuid_votes.insert(key, vote.clone());\n self.recent_votes.push(vote);\n }\n-\n- /// Rebuild edge weights from deduped uuid votes (load path — no rollback).\n- pub fn ingest_uuid_vote(&mut self, vote: VoteData, actor_uuid: &str) {\n- let a_idx = self.ensure_item(&vote.a);\n- let b_idx = self.ensure_item(&vote.b);\n- let (i, j) = if a_idx < b_idx {\n- (a_idx, b_idx)\n- } else {\n- (b_idx, a_idx)\n- };\n- self.apply_weights(&vote, a_idx, b_idx);\n- self.uuid_votes.insert((actor_uuid.to_string(), i, j), vote);\n- }\n }\n \n /// Structured data imported from Reddit or elsewhere.\n@@ -179,7 +99,7 @@ pub struct NodeState {\n /// Ephemeral display view (Reddit title/author/etc.; not event-logged).\n pub data: Option,\n pub children: HashSet,\n- pub local_ranking: GroupState,\n+ pub votes: ScopeVotes,\n }\n \n impl NodeState {\n@@ -242,7 +162,7 @@ impl GlobalTree {\n if let Some(node) = self.nodes.get_mut(parent) {\n node.children.insert(vote.a.clone());\n node.children.insert(vote.b.clone());\n- node.local_ranking.apply_vote(vote, actor_uuid);\n+ node.votes.apply_vote(vote, actor_uuid);\n }\n }\n \n@@ -276,6 +196,7 @@ impl GlobalTree {\n #[cfg(test)]\n mod tests {\n use super::*;\n+ use crate::ranking::edge_weight_sum;\n \n fn vote(ts: i64, a: &str, b: &str, l: i32, r: i32, pseudonym: &str) -> VoteData {\n VoteData {\n@@ -310,26 +231,23 @@ mod tests {\n \n #[test]\n fn same_uuid_replaces_prior_vote_on_pair() {\n- let mut g = GroupState::new();\n+ let mut scope = ScopeVotes::default();\n let uuid = \"u1\";\n- g.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), uuid);\n- let first_total: f64 = g.edges.values().sum();\n- assert_eq!(first_total, 3.0);\n+ scope.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), uuid);\n+ assert_eq!(edge_weight_sum(&scope), 3.0);\n \n- g.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), uuid);\n- let second_total: f64 = g.edges.values().sum();\n- assert_eq!(second_total, 1.0);\n- assert_eq!(g.uuid_votes.len(), 1);\n+ scope.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), uuid);\n+ assert_eq!(edge_weight_sum(&scope), 1.0);\n+ assert_eq!(scope.uuid_votes.len(), 1);\n }\n \n #[test]\n fn different_uuids_both_count() {\n- let mut g = GroupState::new();\n- g.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), \"u1\");\n- g.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), \"u2\");\n- let total: f64 = g.edges.values().sum();\n- assert_eq!(total, 4.0);\n- assert_eq!(g.uuid_votes.len(), 2);\n+ let mut scope = ScopeVotes::default();\n+ scope.apply_vote(vote(1, \"a\", \"b\", 2, 1, \"alice\"), \"u1\");\n+ scope.apply_vote(vote(2, \"a\", \"b\", 0, 1, \"bob\"), \"u2\");\n+ assert_eq!(edge_weight_sum(&scope), 4.0);\n+ assert_eq!(scope.uuid_votes.len(), 2);\n }\n \n #[test]\ndiff --git a/server/src/state.rs b/server/src/state.rs\nindex 8dabc93e95c39cbe18d69596dee79683b384ef86..dcb82ff4beeaac8f0820de0e0131ca1f6bd81dcc 100644\n--- a/server/src/state.rs\n+++ b/server/src/state.rs\n@@ -269,7 +269,7 @@ mod tests {\n use super::{normalize_scope, parse_item_param, AppConfig, AppState};\n use crate::{\n event_log::EventLog, events::Event, path_types::ItemId, projection_apply,\n- projection_store::ProjectionStore, reducer::EntityData,\n+ projection_store::ProjectionStore, ranking::edge_weight_sum, reducer::EntityData,\n };\n \n fn event_record(seq: u64, event: Event) -> crate::events::EventRecord {\n@@ -442,7 +442,7 @@ mod tests {\n assert_eq!(projection_store.last_applied_event_count().unwrap(), 1);\n let first = projection_store.scope_tree(&ItemId::root()).unwrap();\n let first_root = first.get(&ItemId::root()).unwrap();\n- let first_edge_total: f64 = first_root.local_ranking.edges.values().sum();\n+ let first_edge_total = edge_weight_sum(&first_root.votes);\n assert_eq!(first_edge_total, 3.0);\n \n super::catch_up_projection(&log, &projection_store)\n@@ -451,7 +451,7 @@ mod tests {\n assert_eq!(projection_store.last_applied_event_count().unwrap(), 1);\n let second = projection_store.scope_tree(&ItemId::root()).unwrap();\n let second_root = second.get(&ItemId::root()).unwrap();\n- let second_edge_total: f64 = second_root.local_ranking.edges.values().sum();\n+ let second_edge_total = edge_weight_sum(&second_root.votes);\n assert_eq!(second_edge_total, first_edge_total);\n }\n \n@@ -529,9 +529,8 @@ mod tests {\n let root = projected.get(&ItemId::root()).unwrap();\n assert!(root.children.contains(&ItemId::parse(\"alpha\").unwrap()));\n assert!(root.children.contains(&ItemId::parse(\"beta\").unwrap()));\n- assert_eq!(root.local_ranking.idx_to_item.len(), 2);\n- let edge_total: f64 = root.local_ranking.edges.values().sum();\n- assert_eq!(edge_total, 3.0);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 2);\n+ assert_eq!(edge_weight_sum(&root.votes), 3.0);\n }\n \n #[tokio::test]\n@@ -620,7 +619,7 @@ mod tests {\n let root = tree.get(&ItemId::root()).unwrap();\n assert!(root.children.contains(&ItemId::parse(\"beta\").unwrap()));\n assert!(root.children.contains(&ItemId::parse(\"gamma\").unwrap()));\n- assert_eq!(root.local_ranking.idx_to_item.len(), 3);\n+ assert_eq!(crate::ranking::ranked_items(&root.votes).len(), 3);\n }\n \n #[test]\ndiff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs\nindex 67c9f4ab2e1865f8da81b6735dd2a05b87e5e366..fe2671b876f3df77fdfd402dbc845ff1eb3512cd 100644\n--- a/server/src/storage_schema.rs\n+++ b/server/src/storage_schema.rs\n@@ -3,86 +3,53 @@\n //!\n //! Votes are stored as deduped `uuid_votes` entries plus an append-only\n //! `recent_votes` audit list. Edge weights for rank centrality are derived\n-//! from `uuid_votes` on read, not incrementally merged in RocksDB.\n+//! from `uuid_votes` on read, not stored in RocksDB.\n \n-use std::collections::{HashSet};\n+use std::collections::HashSet;\n \n use durable::{Batch, Db, Durable, Leaf, List, Map};\n \n use crate::{\n path_types::ItemId,\n- reducer::{EntityData, GroupState, NodeState, VoteData},\n+ reducer::{EntityData, NodeState, ScopeVotes, VoteData, UuidVoteKey, uuid_vote_key},\n storage_dto::{\n decode_entity_data, decode_vote, encode_entity_data, encode_vote, parse_stored_id,\n StoredEntityDataV1, StoredVoteV1,\n },\n };\n \n-/// `(actor_uuid, min_item_id, max_item_id)` — one vote slot per human per pair.\n-pub type UuidVoteKey = (String, String, String);\n-\n /// One node in the fractal tree, exploded into precisely-updatable collections.\n #[derive(Durable)]\n #[allow(dead_code)]\n pub struct NodeSchema {\n- /// Presence marker (a node \"exists\" once ensured/voted/imported).\n pub present: Leaf,\n- /// Domain-specific derived view (Reddit title/author/…); absent => None.\n pub data: Leaf,\n- /// Child ids (a set; value is always `true`).\n pub children: Map>,\n- /// Latest vote per actor per unordered pair; edges are derived from this on read.\n pub uuid_votes: Map>,\n- /// Recent votes, append-only oldest-first (cap applied on read).\n pub recent_votes: List>,\n- /// When ephemeral Reddit display content was last fetched (ms); absent after eviction.\n pub fetched_at: Leaf,\n }\n \n-/// The single database root: nodes, identity maps, view counts, and metadata.\n #[derive(Durable)]\n #[allow(dead_code)]\n pub struct Store {\n pub nodes: Map,\n- /// Global pseudonym → actor UUID (Sybil dedup anchor).\n pub pseudonyms: Map>,\n pub proj_meta: Map>,\n pub view_counts: Map>,\n pub view_meta: Map>,\n }\n \n-/// Max recent votes returned when loading a node (query-time cap only).\n pub const RECENT_VOTES_CAP: u64 = 200;\n \n fn id_key(id: &ItemId) -> String {\n id.as_str().to_string()\n }\n \n-fn pair_keys(a: &ItemId, b: &ItemId) -> (String, String) {\n- let ak = id_key(a);\n- let bk = id_key(b);\n- if ak <= bk {\n- (ak, bk)\n- } else {\n- (bk, ak)\n- }\n-}\n-\n-pub fn uuid_vote_key(actor_uuid: &str, a: &ItemId, b: &ItemId) -> UuidVoteKey {\n- let (lo, hi) = pair_keys(a, b);\n- (actor_uuid.to_string(), lo, hi)\n-}\n-\n-/// Path to a node by id.\n pub fn node(id: &ItemId) -> durable::Path {\n Store::root().nodes().key(&id_key(id))\n }\n \n-// ---------------------------------------------------------------------------\n-// Reconstruction (durable -> in-memory)\n-// ---------------------------------------------------------------------------\n-\n-/// Reconstruct a node's in-memory state, or `None` if the node does not exist.\n pub fn load_node_state(db: &Db, id: &ItemId) -> durable::Result> {\n let np = node(id);\n let present = np.present().get(db)?.unwrap_or(false);\n@@ -100,47 +67,39 @@ pub fn load_node_state(db: &Db, id: &ItemId) -> durable::Result) -> durable::Result {\n- let mut group = GroupState::new();\n+fn load_scope_votes(db: &Db, np: &durable::Path) -> durable::Result {\n+ let mut votes = ScopeVotes::default();\n \n for (key, stored) in np.uuid_votes().iter(db)? {\n- let (actor_uuid, _lo, _hi) = key;\n let vote = decode_vote(stored).map_err(durable::Error::Deserialize)?;\n- group.ingest_uuid_vote(vote, &actor_uuid);\n+ votes.uuid_votes.insert(key, vote);\n }\n \n let stored = np.recent_votes().iter(db)?;\n let cap = RECENT_VOTES_CAP as usize;\n let start = stored.len().saturating_sub(cap);\n- group.recent_votes = stored[start..]\n+ votes.recent_votes = stored[start..]\n .iter()\n .map(|s| decode_vote(s.clone()).map_err(durable::Error::Deserialize))\n .collect::, _>>()?;\n \n- Ok(group)\n+ Ok(votes)\n }\n \n fn parse_storage_id(s: &str) -> durable::Result {\n parse_stored_id(s).map_err(durable::Error::Deserialize)\n }\n \n-// ---------------------------------------------------------------------------\n-// Write helpers (event -> reified point updates on a batch)\n-// ---------------------------------------------------------------------------\n-\n-/// Wire a node and its ancestors into the tree exactly like\n-/// [`crate::reducer::GlobalTree::ensure_path`]: set presence and parent→child\n-/// links along the canonical breadcrumb path.\n pub fn ensure_path_writes(batch: &mut Batch, id: &ItemId) {\n let root = ItemId::root();\n batch.write(node(&root).present().set(&true));\n@@ -161,7 +120,6 @@ pub fn ensure_path_writes(batch: &mut Batch, id: &ItemId) {\n }\n }\n \n-/// Reified writes for a validated vote under `parent`.\n pub fn vote_writes(\n batch: &mut Batch,\n parent: &ItemId,\n@@ -182,14 +140,12 @@ pub fn vote_writes(\n Ok(())\n }\n \n-/// Reified writes for ephemeral Reddit display content (not event-logged).\n pub fn entity_content_writes(batch: &mut Batch, id: &ItemId, view: &EntityData, fetched_at: i64) {\n ensure_path_writes(batch, id);\n batch.write(node(id).data().set(&encode_entity_data(view)));\n batch.write(node(id).fetched_at().set(&fetched_at));\n }\n \n-/// Clear cached display content for one node (structure/votes are untouched).\n pub fn entity_content_clear_writes(batch: &mut Batch, id: &ItemId) {\n batch.write(node(id).data().delete());\n batch.write(node(id).fetched_at().delete());\n@@ -199,6 +155,7 @@ pub fn entity_content_clear_writes(batch: &mut Batch, id: &ItemId) {\n mod tests {\n use super::*;\n use crate::identity::{seed_default_pseudonym, DEFAULT_ACTOR_UUID, DEFAULT_PSEUDONYM};\n+ use crate::ranking::edge_weight_sum;\n \n fn sample_vote(ts: i64, a: &str, b: &str, l: i32, r: i32) -> VoteData {\n VoteData {\n@@ -213,7 +170,7 @@ mod tests {\n }\n \n #[test]\n- fn vote_roundtrip_reconstructs_group_state() {\n+ fn vote_roundtrip_reconstructs_ranking() {\n let dir = tempfile::tempdir().unwrap();\n let db = Db::open(dir.path()).unwrap();\n seed_default_pseudonym(&db).unwrap();\n@@ -225,11 +182,8 @@ mod tests {\n batch.commit().unwrap();\n \n let node_state = load_node_state(&db, &parent).unwrap().unwrap();\n- let g = &node_state.local_ranking;\n- assert_eq!(g.idx_to_item.len(), 2);\n- let edge_total: f64 = g.edges.values().sum();\n- assert_eq!(edge_total, 3.0);\n- assert_eq!(g.recent_votes.len(), 1);\n+ assert_eq!(edge_weight_sum(&node_state.votes), 3.0);\n+ assert_eq!(node_state.votes.recent_votes.len(), 1);\n assert!(node_state.children.contains(&ItemId::opaque(\"alpha\")));\n assert!(node_state.children.contains(&ItemId::opaque(\"beta\")));\n }\n@@ -263,10 +217,9 @@ mod tests {\n .unwrap();\n batch.commit().unwrap();\n \n- let g = &load_node_state(&db, &parent).unwrap().unwrap().local_ranking;\n- let edge_total: f64 = g.edges.values().sum();\n- assert_eq!(edge_total, 1.0);\n- assert_eq!(g.uuid_votes.len(), 1);\n+ let votes = &load_node_state(&db, &parent).unwrap().unwrap().votes;\n+ assert_eq!(edge_weight_sum(votes), 1.0);\n+ assert_eq!(votes.uuid_votes.len(), 1);\n }\n \n #[test]\n@@ -293,15 +246,8 @@ mod tests {\n );\n \n let node_state = load_node_state(&db, &parent).unwrap().unwrap();\n- assert_eq!(node_state.local_ranking.recent_votes.len(), RECENT_VOTES_CAP as usize);\n- assert_eq!(\n- node_state\n- .local_ranking\n- .recent_votes\n- .first()\n- .map(|v| v.ts),\n- Some(10)\n- );\n+ assert_eq!(node_state.votes.recent_votes.len(), RECENT_VOTES_CAP as usize);\n+ assert_eq!(node_state.votes.recent_votes.first().map(|v| v.ts), Some(10));\n }\n \n #[test]\ndiff --git a/server/tests/integration_ui.rs b/server/tests/integration_ui.rs\nindex cc7a16d756673b95ba336f2d6130eaf40908cc60..40e4cfe1eec36dad29a075fb01aefb4dffd856d0 100644\n--- a/server/tests/integration_ui.rs\n+++ b/server/tests/integration_ui.rs\n@@ -132,7 +132,7 @@ async fn post_ui_record_vote_morphs_ranking_and_persists() {\n let state = create_app_state(cfg).await;\n let tree = state.scope_tree(&ItemId::root()).unwrap();\n let root = tree.get(&ItemId::root()).expect(\"root node after replay\");\n- let ranked = sorter2_server::ranking::ranked_items(&root.local_ranking);\n+ let ranked = sorter2_server::ranking::ranked_items(&root.votes);\n assert_eq!(ranked.len(), 2);\n assert_eq!(ranked[0].item.as_str(), \"alpha\");\n }\n","role":"user"}],"model":"openai/gpt-chat-latest"}