constitution · epochs · watch · epoch 3

comparison

c_4772ee88dbe3 (tommy-mor) vs c_2722a3195825 (tommy-mor)

download prompt · raw event · cmp_cec573d0183409

council reasoning

~anthropic/claude-sonnet-latest · winner B · 8:2 · permalink

Side B implements a substantive, well-tested algorithmic improvement to pair selection (established-component merging, isolate attachment, rank-adjacency zipping) with several new unit tests validating the logic. Side A mostly removes an unrelated demo-counter feature and adds a settlement-worker/caching refactor, which is reasonable plumbing but is dwarfed by dead demo-code removal churn and lacks the depth of new behavior or test coverage seen in B.

~x-ai/grok-latest · winner A · 2:1 · permalink

A lands lasting architecture: a settlement worker that batches vote append/apply, warms and serves a ranking cache, and turns ranking/UI paths to read locks—plus full removal of the demo-counter event/UI surface. B only refines pair-suggestion heuristics (bridge sub-priorities and adjacent-rank zip) with good tests; valuable product logic, but narrower than A’s design and concurrency changes.

openai/gpt-chat-latest · winner A · 3:2 · permalink

Side A introduces a substantial architectural improvement by moving vote persistence and ranking recomputation into a dedicated settlement worker, adding cached ranking reads (`ranked_items_cached`), warming the cache at startup, and switching HTTP paths from write locks to read locks. It also removes obsolete demo-counter code and event types, simplifying the application, whereas Side B improves the pair-selection heuristic with more nuanced bridge and rank-based prioritization plus tests, but its impact is limited to recommendation quality rather than core system architecture and performance.

sides

A — c_4772ee88dbe3 (tommy-mor)

message

[07715165] nice

diff preview

diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index c3c62a76f424010d77a6090c84dd0b82098f573e..da2536112faea313352624cf2ce0ddd0ab3377c1 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -6,7 +6,7 @@ use axum::{
 use std::collections::HashMap;
 
 use crate::{
-    html::{demo_counter_panel, js_string_literal, ranking_panel, JsBuilder},
+    html::{js_string_literal, ranking_panel, JsBuilder},
     parser::parse_reddit_url,
     parser_render::parser_panel_morph,
     state::AppState,
@@ -35,13 +35,6 @@ pub async fn post_ui_html(
     };
 
     match action {
-        HtmlUiAction::BumpDemoCounter => {
-            let count = state.bump_demo_counter().await;
-            let panel = demo_counter_panel(count, state.event_log.path().to_string_lossy().as_ref());
-            JsBuilder::new()
-                .morph_selector("#demo-counter-panel", panel)
-                .into_response()
-        }
         HtmlUiAction::RecordVote {
             a,
             b,
@@ -54,8 +47,8 @@ pub async fn post_ui_html(
             {
                 return ui_js_warn(&e).into_response();
             }
-            let mut group = state.group.write().await;
-            let panel = ranking_panel(&mut group);
+            let group = state.group.read().await;
+            let panel = ranking_panel(&group);
             JsBuilder::new()
                 .morph_selector("#ranking-panel", panel)
                 .into_response()
@@ -87,20 +80,6 @@ mod tests {
         assert!(matches!(err, HtmlUiParseError::MissingRpc));
     }
 
-    #[test]
-    fn bump_action_deserializes() {
-        let template = serde_json::json!({ "action": "bump_demo_counter" });
-        let mut form = HashMap::new();
-        form.insert(
-            UI_RPC_FIELD.to_string(),
-            serde_json::to_string(&template).unwrap(),
-        );
-        assert_eq!(
-            parse_html_ui_from_form(&form).unwrap(),
-            HtmlUiAction::BumpDemoCounter
-        );
-    }
-
     #[test]
     fn record_vote_action_deserializes() {
         let template = serde_json::json!({
diff --git a/server/src/events.rs b/server/src/events.rs
index b969242534e184d4f0a689543a479670b08a18df..eff80aef0257f706d2341f666e63d6a3d921bf6e 100644
--- a/server/src/events.rs
+++ b/server/src/events.rs
@@ -5,8 +5,6 @@ use serde::{Deserialize, Serialize};
 pub enum Event {
     /// Page view recorded (path → counter in views.json).
     ViewRecorded { path: String, ts: i64 },
-    /// Demo counter bump from `POST /ui` (persisted in the single JSONL log).
-    DemoCounterBumped { ts: i64, value: u64 },
     /// Pairwise comparison vote (replayed into [`crate::reducer::GroupState`] on boot).
     VoteRecorded {
         ts: i64,
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index 5b1d0b5a887d89e7e80796aa7a6c8ed5baaf2782..d69ed962b5c8625bc83c933b1825f2cc1d0868e2 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -13,7 +13,7 @@ use crate::{
     form_template::template_json_compact,
     parser_action::ParserAction,
     parser_render::parser_panel,
-    ranking::ranked_items,
+    ranking::ranked_items_cached,
     reducer::GroupState,
     state::AppState,
     ui_action::UI_RPC_FIELD,
@@ -199,10 +199,8 @@ fn layout(title: &str, body: Markup, views: u64, theme: &str, theme_next: &str)
     }
 }
 
-pub fn ranking_panel(group: &mut GroupState) -> Markup {
-    const MAX_ITERS: usize = 10_000;
-    const TOL: f64 = 1e-8;
-    let items = ranked_items(group, MAX_ITERS, TOL);
+pub fn ranking_panel(group: &GroupState) -> Markup {
+    let items = ranked_items_cached(group);
     html! {
         section id="ranking-panel" class="demo-panel" {
             h2 { "Ranking" }
@@ -260,35 +258,6 @@ pub fn vote_panel() -> Markup {
 }
 
 
-pub fn demo_counter_panel(count: u64, event_log_path: &str) -> Markup {
-    let rpc = template_json_compact(&serde_json::json!({ "action": "bump_demo_counter" }))
-        .expect("rpc json");
-    html! {
-        section id="demo-counter-panel" class="demo-panel" {
-            h1 { "sorter2" }
-            p class="muted" {
-                "Pairwise ranking scaffold — votes persist to JSONL and replay on boot."
-            }
-            p class="demo-count" {
-                strong { "Counter: " }
-                span id="demo-count-value" { (count) }
-            }
-            p class="muted small" {
-                "Event log: " code { (event_log_path) }
-            }
-            form method="post" action="/ui" id="demo-bump-form" {
-                input type="hidden" name=(UI_RPC_FIELD) value=(rpc);
-                button type="submit" class="btn-primary" { "Bump (POST /ui → eval JS)" }
-            }
-            p class="muted small" {
-                "Uses hidden "
-                code { "__rpc__" }
-                " JSON + Idiomorph morph — no full page reload."
-            }
-        }
-    }
-}
-
 pub async fn home(
     State(state): State<AppState>,
     jar: CookieJar,
@@ -297,16 +266,15 @@ pub async fn home(
     let path = uri.path().to_string();
     state.views.increment(path.clone());
     let views = state.views.get_views(&path);
-    let count = *state.demo_counter.read().await;
     let theme = theme_from_jar(&jar);
     let theme_next = theme_next_from_uri(&uri);
-    let mut group = state.group.write().await;
+    let group = state.group.read().await;
     let empty_action = ParserAction::suggest(String::new(), None);
     let body = html! {
+        h1 { "sorter2" }
         (parser_panel("", &empty_action))
         (vote_panel())
-        (ranking_panel(&mut group))
-        (demo_counter_panel(count, state.event_log.path().to_string_lossy().as_ref()))
+        (ranking_panel(&group))
     };
     layout("sorter2", body, views, theme, &theme_next)
 }
diff --git a/server/src/lib.rs b/server/src/lib.rs
index 6716c5b282e7980a7a0f03d63ad8b25eda61cc55..fa423640d598f4ba97a5885d228e78d7b97f7a22 100644
--- a/server/src/lib.rs
+++ b/server/src/lib.rs
@@ -9,6 +9,7 @@ pub mod parser_render;
 pub mod path_types;
 pub mod ranking;
 pub mod reducer;
+pub mod settlement;
 pub mod state;
 pub mod ui_action;
 pub mod views;
diff --git a/server/src/ranking.rs b/server/src/ranking.rs
index 89d3280126a8d8f841721ce8cb63ff735d68752a..2d706762792ba9239bb3f1c2e4974a2fde908013 100644
--- a/server/src/ranking.rs
+++ b/server/src/ranking.rs
@@ -91,6 +91,11 @@ pub fn compute_group_ranking(group: &mut GroupState, max_iters: usize, tol: f64)
 
 pub fn ranked_items(group: &mut GroupState, max_iters: usize, tol: f64) -> Vec<RankedItem> {
     compute_group_ranking(group, max_iters, tol);
+    ranked_items_cached(group)
+}
+
+/// Read cached scores without recomputing (HTTP fast path).
+pub fn ranked_items_cached(group: &GroupState) -> Vec<RankedItem> {
     let mut items: Vec<RankedItem> = group
         .idx_to_item
         .iter()
@@ -105,7 +110,12 @@ pub fn ranked_items(group: &mut GroupState, max_iters: usize, tol: f64) -> Vec<R
     items
 }
 
-fn compute_scores_from_edges(n: usize, edges: impl Iterator<Item = ((usize, usize), f64)>, max_iters: usize, tol: f64) -> Vec<f64> {
+pub fn compute_scores_from_edges(
+    n: usize,
+    edges: impl Iterator<Item = ((usize, usize), f64)>,
+    max_iters: usize,
+    tol: f64,
+) -> Vec<f64> {
     if n == 0 {
         return vec![];
     }
diff --git a/server/src/settlement.rs b/server/src/settlement.rs
new file mode 100644
index 0000000000000000000000000000000000000000..1f722ceaea62cda22c28ab71551f259fbf049b81
--- /dev/null
+++ b/server/src/settlement.rs
@@ -0,0 +1,114 @@
+use std::sync::Arc;
+
+use tokio::sync::{mpsc, oneshot, RwLock};
+
+use crate::{
+    event_log::EventLog,
+    events::Event,
+    ranking::compute_scores_from_edges,
+    reducer::{GroupState, VoteData},
+};
+
+const MAX_ITERS: usize = 10_000;
+const TOL: f64 = 1e-8;
+
+pub struct SettlementCommand {
+    pub vote: VoteData,
+    pub event: Event,
+    pub reply: oneshot::Sender<Result<(), String>>,
+}
+
+#[derive(Clone)]
+pub struct SettlementClient {
+    tx: mpsc::Sender<SettlementCommand>,
+}
+
+impl SettlementClient {
+    pub fn spawn(group: Arc<RwLock<GroupState>>, event_log: Arc<EventLog>) -> Self {
+        let (tx, rx) = mpsc::channel(64);
+        tokio::spawn(settlement_worker(rx, group, event_log));
+        Self { tx }
+    }
+
+    pub async fn record_vote(&self, vote: VoteData, event: Event) -> Result<(), String> {
+        let (reply, rx) = oneshot::channel();
+        self.tx
+            .send(SettlementCommand {
+                vote,
+                event,
+                reply,
+            })
+            .await
+            .map_err(|_| "settlement worker stopped".to_string())?;
+        rx.await
+            .map_err(|_| "settlement worker stopped".to_string())?
+    }
+}
+
+async fn settlement_worker(
+    mut rx: mpsc::Receiver<SettlementCommand>,
+    group: Arc<RwLock<GroupState>>,
+    event_log: Arc<EventLog>,
+) {
+    while let Some(first) = rx.recv().await {
+        let mut batch = vec![first];
+        while let Ok(more) = rx.try_recv() {
+            batch.push(more);
+        }
+
+        let mut disk_err: Option<String> = None;
+        for cmd in &batch {
+            if let Err(e) = event_log.append(&cmd.event).await {
+                disk_err = Some(e.to_string());
+                break;
+            }
+        }
+
+        if let Some(err) = disk_err {
+            for cmd in batch {
+                let _ = cmd.reply.send(Err(err.clone()));
+            }
+            continue;
+        }
+
+        let (edges, n) = {
+            let mut w = group.write().await;
+            for cmd in &batch {
+                w.apply_vote(cmd.vote.clone());
+            }
+            (w.edges.clone(), w.idx_to_item.len())
+        };
+
+        let new_scores = compute_scores_from_edges(
+            n,
+            edges.iter().map(|(&k, &v)| (k, v)),
+            MAX_ITERS,
+            TOL,
+        );
+
+        {
+            let mut w = group.write().await;
+            w.cached_scores = new_scores;
+            w.dirty = false;
+        }
+
+        for cmd in batch {
+            let _ = cmd.reply.send(Ok(()));
+        }
+    }
+}
+
+/// Compute ranking cache from current in-memory edges (startup replay only).
+pub fn warm_ranking_cache(group: &mut GroupState) {
+    if !group.dirty {
+        return;
+    }
+    let n = group.idx_to_item.len();
+    group.cached_scores = compute_scores_from_edges(
+        n,
+        group.edges.iter().map(|(&k, &v)| (k, v)),
+        MAX_ITERS,
+        TOL,
+    );
+    group.dirty = false;
+}
diff --git a/server/src/state.rs b/server/src/state.rs
index 8ec9902e2ecc31cf8208f7ad6365891dc5537eed..1922541a4064c2de1df2d993a461cae783320e05 100644
--- a/server/src/state.rs
+++ b/server/src/state.rs
@@ -6,6 +6,7 @@ use crate::{
     event_log::EventLog,
     events::Event,
     reducer::{GroupState, VoteData},
+    settlement::{warm_ranking_cache, SettlementClient},
     views::ViewStore,
 };
 
@@ -38,8 +39,8 @@ pub struct AppState {
     pub cfg: Arc<AppConfig>,
     pub event_log: Arc<EventLog>,
     pub views: ViewStore,
-    pub demo_counter: Arc<RwLock<u64>>,
     pub group: Arc<RwLock<GroupState>>,
+    settlement: SettlementClient,
 }
 
 impl AppState {
@@ -48,14 +49,10 @@ impl AppState {
         let views_path = format!("{}/views.json", cfg.data_dir);
         let views = ViewStore::new(&views_path);
 
-        let mut demo_counter: u64 = 0;
         let mut group = GroupState::new();
         if let Ok((events, _)) = event_log.load_all().await {
             for ev in events {
                 match ev {
-                    Event::DemoCounterBumped { value, .. } => {
-                        demo_counter = demo_counter.max(value);
-                    }
                     Event::VoteRecorded {
                         ts,
                         a,
@@ -74,30 +71,20 @@ impl AppState {
             }
         }
 
+       

… preview truncated; 6,096 characters omitted

download full diff A

B — c_2722a3195825 (tommy-mor)

message

[5db58b98] Improve vote pair selection for spanning trees and rank refinement.

Prefer attaching unranked items to established components before comparing
isolates, then zip down adjacent rank-centrality pairs once the pool is fully
connected, skipping pairs that already have votes.

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

diff preview

diff --git a/server/src/pair.rs b/server/src/pair.rs
index 54b5d2417e9dba04ed8df422156e274c2b2f76b2..c14de4b0502c8b5a17cddf3746077739d56e03e0 100644
--- a/server/src/pair.rs
+++ b/server/src/pair.rs
@@ -3,13 +3,21 @@
 //! Pair selection prefers **bridge** votes — comparisons between items in
 //! different connected components of the voted-pairs graph — so the pool
 //! merges into one ranking group before refining within it.
+//!
+//! Among unvoted bridges, prefer merging established voted components, then
+//! attaching a never-voted child to an established component, and only then
+//! comparing two never-voted children (so the voted graph grows as one tree).
+//!
+//! Once every pool child sits in one voted component, refinement **zips** down
+//! the rank-centrality order: prefer 1 vs 2, then 2 vs 3, and so on, skipping
+//! pairs that already have a vote.
 
 use rand::seq::SliceRandom;
 use std::collections::{HashMap, HashSet};
 
 use crate::{
     path_types::ItemId,
-    ranking::connected_components_from_voted_pairs,
+    ranking::{connected_components_from_voted_pairs, ranked_items},
     reducer::{GlobalTree, GroupState},
 };
 
@@ -28,36 +36,77 @@ fn pair_is_voted(group: &GroupState, a: &ItemId, b: &ItemId) -> bool {
     group.voted_pairs.contains(&(i, j))
 }
 
-/// Component id per pool item: voted-pairs graph components plus one id per
-/// never-voted child.
-fn component_ids(group: &GroupState, pool: &[ItemId]) -> HashMap<ItemId, usize> {
+/// Voted-pairs layout for pool items: component id per item plus which ids are
+/// multi-node voted components (ranked groups in the UI).
+struct ComponentLayout {
+    ids: HashMap<ItemId, usize>,
+    established: HashSet<usize>,
+}
+
+fn component_layout(group: &GroupState, pool: &[ItemId]) -> ComponentLayout {
     let n = group.idx_to_item.len();
     let (comps, isolates) =
         connected_components_from_voted_pairs(n, group.voted_pairs.iter().copied());
 
-    let mut out: HashMap<ItemId, usize> = HashMap::new();
+    let mut established = HashSet::new();
+    let mut ids: HashMap<ItemId, usize> = HashMap::new();
     for (comp_idx, comp) in comps.iter().enumerate() {
+        if comp.len() >= 2 {
+            established.insert(comp_idx);
+        }
         for &idx in comp {
             if idx < n {
-                out.insert(group.idx_to_item[idx].clone(), comp_idx);
+                ids.insert(group.idx_to_item[idx].clone(), comp_idx);
             }
         }
     }
     let mut next = comps.len();
     for &idx in &isolates {
         if idx < n {
-            out.insert(group.idx_to_item[idx].clone(), next);
+            ids.insert(group.idx_to_item[idx].clone(), next);
             next += 1;
         }
     }
     for item in pool {
-        out.entry(item.clone()).or_insert_with(|| {
+        ids.entry(item.clone()).or_insert_with(|| {
             let id = next;
             next += 1;
             id
         });
     }
-    out
+    ComponentLayout { ids, established }
+}
+
+/// Every pool child shares one multi-node voted component (spanning tree phase done).
+fn pool_fully_connected(layout: &ComponentLayout, pool: &[ItemId]) -> bool {
+    if pool.len() < 2 {
+        return false;
+    }
+    let mut comp_id = None;
+    for item in pool {
+        let Some(id) = layout.ids.get(item) else {
+            return false;
+        };
+        if !layout.established.contains(id) {
+            return false;
+        }
+        match comp_id {
+            None => comp_id = Some(*id),
+            Some(expected) if expected == *id => {}
+            _ => return false,
+        }
+    }
+    comp_id.is_some()
+}
+
+/// Pool children that appear in `group`, sorted best rank first.
+fn ranked_pool_order(group: &GroupState, pool: &[ItemId]) -> Vec<ItemId> {
+    let pool_set: HashSet<_> = pool.iter().collect();
+    ranked_items(group)
+        .into_iter()
+        .map(|r| r.item)
+        .filter(|id| pool_set.contains(id))
+        .collect()
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@@ -72,19 +121,108 @@ enum PairPriority {
     WithinVoted = 3,
 }
 
-fn pair_priority(
+/// Tie-break among unvoted bridge pairs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+enum BridgeSubPriority {
+    /// Both endpoints lie in established (multi-node) voted components.
+    MergeEstablished = 0,
+    /// One established component member and one never-voted child.
+    AttachIsolate = 1,
+    /// Two never-voted children (separate singleton components).
+    IsolatePair = 2,
+}
+
+/// Tie-break among within-component pairs once the pool is one connected group.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+struct WithinSubPriority {
+    /// 1 = adjacent ranks (i vs i+1); larger = farther apart in the order.
+    rank_gap: usize,
+    /// min rank index of the two — zip from the top (1 vs 2 before 2 vs 3).
+    zip_index: usize,
+}
+
+const WITHIN_SUB_WORST: WithinSubPriority = WithinSubPriority {
+    rank_gap: usize::MAX,
+    zip_index: usize::MAX,
+};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
+struct PairSortKey {
+    priority: PairPriority,
+    bridge_sub: BridgeSubPriority,
+    within_sub: WithinSubPriority,
+}
+
+fn item_in_established(layout: &ComponentLayout, item: &ItemId) -> bool {
+    layout
+        .ids
+        .get(item)
+        .is_some_and(|id| layout.established.contains(id))
+}
+
+fn bridge_sub_priority(layout: &ComponentLayout, a: &ItemId, b: &ItemId) -> BridgeSubPriority {
+    let a_est = item_in_established(layout, a);
+    let b_est = item_in_established(layout, b);
+    match (a_est, b_est) {
+        (true, true) => BridgeSubPriority::MergeEstablished,
+        (true, false) | (false, true) => BridgeSubPriority::AttachIsolate,
+        (false, false) => BridgeSubPriority::IsolatePair,
+    }
+}
+
+fn within_sub_priority(
+    group: &GroupState,
+    pool: &[ItemId],
+    layout: &ComponentLayout,
+    a: &ItemId,
+    b: &ItemId,
+) -> WithinSubPriority {
+    if !pool_fully_connected(layout, pool) {
+        return WITHIN_SUB_WORST;
+    }
+    let order = ranked_pool_order(group, pool);
+    let (Some(i), Some(j)) = (order.iter().position(|x| x == a), order.iter().position(|x| x == b))
+    else {
+        return WITHIN_SUB_WORST;
+    };
+    WithinSubPriority {
+        rank_gap: i.abs_diff(j),
+        zip_index: i.min(j),
+    }
+}
+
+fn pair_sort_key(
     group: &GroupState,
-    components: &HashMap<ItemId, usize>,
+    pool: &[ItemId],
+    layout: &ComponentLayout,
     a: &ItemId,
     b: &ItemId,
-) -> PairPriority {
+) -> PairSortKey {
     let voted = pair_is_voted(group, a, b);
-    let bridge = components.get(a) != components.get(b);
-    match (bridge, voted) {
+    let bridge = layout.ids.get(a) != layout.ids.get(b);
+    let priority = match (bridge, voted) {
         (true, false) => PairPriority::BridgeUnvoted,
         (false, false) => PairPriority::WithinUnvoted,
         (true, true) => PairPriority::BridgeVoted,
         (false, true) => PairPriority::WithinVoted,
+    };
+    let bridge_sub = if priority == PairPriority::BridgeUnvoted {
+        bridge_sub_priority(layout, a, b)
+    } else {
+        BridgeSubPriority::MergeEstablished
+    };
+    let within_sub = if matches!(
+        priority,
+        PairPriority::WithinUnvoted | PairPriority::WithinVoted
+    ) {
+        within_sub_priority(group, pool, layout, a, b)
+    } else {
+        WITHIN_SUB_WORST
+    };
+    PairSortKey {
+        priority,
+        bridge_sub,
+        within_sub,
     }
 }
 
@@ -109,9 +247,12 @@ fn candidate_pairs(pool: &[ItemId], exclude: Option<(&ItemId, &ItemId)>) -> Vec<
 
 /// Pick the next pair to vote on within `pool`.
 ///
-/// 1. Prefer unvoted **bridge** pairs (connect separate ranking components).
-/// 2. Then unvoted within-component pairs (refinement).
-/// 3. Then already-voted pairs (re-compare).
+/// 1. Prefer unvoted **bridge** pairs (connect separate ranking components),
+///    with sub-priority: merge established components, attach an isolate to
+///    established, then compare two isolates.
+/// 2. Then unvoted within-component pairs; when the pool is one connected group,
+///    prefer adjacent ranks (1 vs 2, 2 vs 3, …) in order, skipping voted pairs.
+/// 3. Then already-voted pairs (re-compare), with the same zip ordering.
 pub fn suggest_next_pair_in_pool(
     group: &GroupState,
     pool: &[ItemId],
@@ -121,15 +262,15 @@ pub fn suggest_next_pair_in_pool(
     if candidates.is_empty() {
         return None;
     }
-    let components = component_ids(group, pool);
+    let layout = component_layout(group, pool);
     let best = candidates
         .iter()
-        .map(|(a, b)| (pair_priority(group, &components, a, b), (a, b)))
-        .min_by_key(|(p, _)| *p)?
+        .map(|(a, b)| (pair_sort_key(group, pool, &layout, a, b), (a, b)))
+        .min_by_key(|(k, _)| *k)?
         .0;
     let best_pairs: Vec<(ItemId, ItemId)> = candidates
         .into_iter()
-        .filter(|(a, b)| pair_priority(group, &components, a, b) == best)
+        .filter(|(a, b)| pair_sort_key(group, pool, &layout, a, b) == best)
         .collect();
     best_pairs.choose(&mut rand::thread_rng()).cloned()
 }
@@ -303,6 +444,38 @@ mod tests {
         assert!(from_ab && from_cd, "expected bridge pair, got {:?}", chosen);
     }
 
+    #[test]
+    fn suggest_prefers_attach_over_isolate_pair_among_many_unranked() {
+        let parent = ItemId::parse("reddit.com/r/rust").unwrap();
+        let mut tree = seed_children(
+            &parent,
+            &[
+                "reddit.com/r/rust/a",
+                "reddit.com/r/rust/b",
+                "reddit.com/r/rust/c",
+                "reddit.com/r/rust/d",
+                "reddit.com/r/rust/e",
+            ],
+        );
+        let ab =
+            VoteData::from_recorded(1, "reddit.com/r/rust/a", "reddit.com/r/rust/b", 2, 1).unwrap();
+        tree.apply_vote(&parent, ab);
+        let group = tree.get(&parent).unwrap().local_ranking.clone();
+        let pool = children_of(&tree, &parent);
+        let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();
+        let chosen = pair_set(&pair);
+        let from_ab =
+            chosen.contains("reddit.com/r/rust/a") || chosen.contains("reddit.com/r/rust/b");
+        let from_cde = chosen.contains("reddit.com/r/rust/c")
+            || chosen.contains("reddit.com/r/rust/d")
+            || chosen.contains("reddit.com/r/rust/e");
+        assert!(
+            from_ab && from_cde,
+            "expected ranked+unranked attach, got {:?}",
+            chosen
+        );
+    }
+
     #[test]
     fn suggest_connects_isolate_to_existing_component() {
         let parent = ItemId::parse("reddit.com/r/rust").unwrap();
@@ -325,6 +498,65 @@ mod tests {
         assert!(chosen.contains("reddit.com/r/rust/a") || chosen.contains("reddit.com/r/rust/b"));
     }
 
+    #[test]
+    fn suggest_zips_adjacent_ranks_when_tree_complete() {
+        let parent = ItemId::parse("reddit.com/r/rust").unwrap();
+        let mut tree = seed_children(
+            &parent,
+            &[
+                "reddit.com/r/rust/a",
+                "reddit.com/r/rust/b",
+                "reddit.com/r/rust/c",
+            ],
+        );
+        // Star at a connects all three; b-c is the only unvoted adjacent pair left.
+        for (a, b, l, r) in [
+            ("reddit.com/r/rust/a", "reddit.com/r/rust/b", 3, 1),
+            ("reddit.com/r/rust/a", "reddit.com/r/rust/c", 2, 1),
+        ] {
+            let v = VoteData::from_recorded(1, a, b, l, r).unwrap();
+            tree.apply_vote(&parent, v);
+        }
+        let group = tree.get(&parent).unwrap().local_ranking.clone();
+        let pool = children_of(&tree, &parent);
+        let pair = suggest_next_pair_in_pool(&group, &pool, None).unwrap();
+        let chosen = pair_set(&pair);
+        // a-b and a-c voted;

… preview truncated; 1,687 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.