constitution · epochs · watch · epoch 3

comparison

c_94135a1c4c58 (tommy-mor) vs c_4772ee88dbe3 (tommy-mor)

download prompt · raw event · cmp_110d19e4898d34

council reasoning

~anthropic/claude-sonnet-latest · winner A · 6:4 · permalink

Side A fixes a genuine security bug (votes silently falling back to an anonymous actor instead of failing closed), gates the mock-OAuth test backdoor behind an explicit env flag, adds Secure-cookie support and stronger open-redirect sanitization, and backs these with new unit tests plus doc/Cargo.lock pinning improvements. Side B is a reasonable performance refactor (async settlement worker, cached ranking scores) and dead-code removal, but it adds no new tests for the concurrency/caching logic it introduces and its commit message ('nice') reflects low documentation effort, making its lasting correctness harder to verify compared to A's targeted, well-tested security hardening.

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

A hardens production auth (fail-closed vote actors instead of silent anon fallback, mock OAuth gated by env, Secure cookies, tighter return_to sanitization) and adds durable session UX/tests, which is lasting security and correctness. B’s settlement worker and ranking cache are solid core design and demo-counter removal is good cleanup, but they improve an earlier scaffold path rather than matching A’s multi-point security/ownership guarantees.

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

Side A makes several lasting security and correctness improvements: voting now fails closed by requiring a valid authenticated session instead of silently falling back to an anonymous actor, auth cookies gain the Secure flag when appropriate, OAuth mock login is gated behind an environment flag, and return URL sanitization is strengthened with tests to block additional open-redirect forms. Side B contains useful architectural cleanup (removing the demo counter, introducing cached rankings and a settlement worker), but much of it is refactoring/performance-oriented, whereas Side A directly fixes security and authorization behavior with concrete user-facing correctness benefits.

sides

A — c_94135a1c4c58 (tommy-mor)

message

[880eb778] Harden auth: fail-closed votes, mock OAuth gate, Secure cookies.

Also show the current alias in the top nav and pin durable by rev.

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

diff preview

diff --git a/AGENTS.md b/AGENTS.md
index babb889d6fbfb1fa7176c9e6b7544ae17b61dd2e..6e0fd8ebb65d665c9c1438e3275971d62b98fd95 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,11 +10,11 @@ Single Rust web app **`sorter2-server`**: pairwise voting, rank-centrality ranki
 
 - **Bootstrap script**: `./scripts/cursor-env-install.sh` (also run via `.cursor/environment.json` on Cloud Agent boot) installs Playwright Chromium, Babashka, bbin, `clj-paren-repair`, and warms the RocksDB build.
 - **Rust 1.88+** is required (`rust-toolchain.toml`). The Cloud Dockerfile and `cursor-env-install.sh` install **rustup** 1.88.0 first so `cargo` works while Playwright/Clojure bootstrap continues. Do not rely on `/usr/local/cargo` (often missing or stale).
-- **RocksDB / `durable`**: Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS="-C linker=g++"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.
+- **RocksDB / `durable`**: `durable` is an external git dependency (`tommy-mor/durable`, pinned by rev in `server/Cargo.toml`). Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS="-C linker=g++"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.
 - **System packages** for builds: `build-essential`, `g++`, `clang`, `libclang-dev`, `pkg-config`, `libssl-dev`, `openjdk-21-jre-headless` (for `reqwest` / OpenSSL, `librocksdb-sys`, `zstd-sys` / bindgen, and **bbin** / Clojure JVM). The bootstrap sets **`JAVA_HOME`** when Java is present.
 - **Clojure CLI 1.12.0.1530** (used in CI): install from https://clojure.org/guides/install_clojure — needed for `./scripts/clj-test.sh` / Kaocha tests.
 - **Babashka / bbin / clj-paren-repair**: installed by `cursor-env-install.sh` into `~/.local/bin` (bb tasks in `bb.edn`, delimiter repair for Clojure edits).
-- **Playwright** (Spel browser tests in `test/vote_compare.clj`): Chromium via `clojure -M -e "(com.microsoft.playwright.CLI/main ...)"` — run once after clone or use the bootstrap script.
+- **Playwright** (Spel browser tests in `test/vote_compare.clj` / `test/auth_login.clj`): Chromium via `clojure -M -e "(com.microsoft.playwright.CLI/main ...)"` — run once after clone or use the bootstrap script.
 
 ### Commands (see also `TEST.sh`)
 
@@ -34,13 +34,17 @@ Environment variables (defaults in `server/src/state.rs`):
 - `PORT` — default `8080`
 - `SORTER2_DATA_DIR` — default `./data` (created on startup)
 - `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl`
+- `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`)
+- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset)
+- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only)
 
 Health check: `GET /healthz` → `ok`.
 
-Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Example vote:
+Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Votes require a session cookie (sign in via `/login`). Example vote:
 
 ```bash
 curl -sf -X POST http://127.0.0.1:8080/ui \
+  --cookie "sorter2_session=..." \
   --data-urlencode '__rpc__={"action":"record_vote","a":"alpha","b":"beta","ratio_left":2,"ratio_right":1}'
 ```
 
diff --git a/Cargo.lock b/Cargo.lock
index aa02997ad85777195f135bfd9456bcee0fc9a590..1f8690f3e486d099577a32c2ece48caf57ea7160 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -414,7 +414,7 @@ dependencies = [
 [[package]]
 name = "durable"
 version = "0.2.0"
-source = "git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
+source = "git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
 dependencies = [
  "ciborium",
  "durable-derive",
@@ -426,7 +426,7 @@ dependencies = [
 [[package]]
 name = "durable-derive"
 version = "0.2.0"
-source = "git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
+source = "git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
 dependencies = [
  "proc-macro2",
  "quote",
diff --git a/server/Cargo.toml b/server/Cargo.toml
index dfa39beddecfa37dcdeaa602cb30f4b547528fbb..bd88687fb0ba47d68f2c08eb5e11d0e08b7c4398 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -25,7 +25,7 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }
 rand = "0.8"
 urlencoding = "2"
 url = "2"
-durable = { git = "https://github.com/tommy-mor/durable.git", branch = "main" }
+durable = { git = "https://github.com/tommy-mor/durable.git", rev = "a6c14eaa809693140eea0c22b07ef24d8e74adaf" }
 
 [dev-dependencies]
 reqwest = { version = "0.12", features = ["json"] }
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index b86581b1f337650564274254d840e8a75b49524d..9da62ffbed07eb28729aa3160bf33b07ce0d7945 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -71,10 +71,16 @@ pub async fn post_ui_html(
                 return resp;
             }
             let parent = parent_from_scope(&scope);
-            let actor = resolve_vote_actor(
+            let actor = match resolve_vote_actor(
                 state.projection_store.db(),
                 session_id_from_jar(&jar).as_deref(),
-            );
+            ) {
+                Ok(actor) => actor,
+                Err(_) => {
+                    return vote_auth_redirect(&state, &jar)
+                        .unwrap_or_else(|| login_redirect_js().into_response());
+                }
+            };
             if let Err(e) = state
                 .record_vote(&parent, &a, &b, ratio_left, ratio_right, &actor)
                 .await
diff --git a/server/src/auth/config.rs b/server/src/auth/config.rs
index a1f042c655bf3e5234eeb87a7d889f64592807fb..a5976af9a52ea207b35ae87bd1fe927c47a477ca 100644
--- a/server/src/auth/config.rs
+++ b/server/src/auth/config.rs
@@ -1,9 +1,42 @@
 pub const AUTH_RETURN_COOKIE: &str = "sorter2_auth_return";
 
+/// Allow `mock_user` on `/auth/github` (test harness only).
+pub fn mock_oauth_allowed() -> bool {
+    matches!(
+        std::env::var("SORTER2_ALLOW_MOCK_OAUTH").as_deref(),
+        Ok("1") | Ok("true") | Ok("TRUE")
+    )
+}
+
+/// Set the Secure flag on auth cookies when serving over HTTPS.
+pub fn cookies_secure() -> bool {
+    std::env::var("SORTER2_BASE_URL")
+        .map(|u| u.starts_with("https://"))
+        .unwrap_or(false)
+}
+
 pub fn sanitize_return_to(raw: &str) -> String {
     let s = raw.trim();
-    if s.is_empty() || !s.starts_with('/') || s.starts_with("//") {
+    if s.is_empty() || !s.starts_with('/') || s.starts_with("//") || s.starts_with("/\\") {
+        return "/".to_string();
+    }
+    // Reject scheme-relative and protocol-smuggling forms.
+    if s.contains("://") || s.contains('\\') {
         return "/".to_string();
     }
     s.to_string()
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn sanitize_return_to_blocks_open_redirects() {
+        assert_eq!(sanitize_return_to(""), "/");
+        assert_eq!(sanitize_return_to("//evil.com"), "/");
+        assert_eq!(sanitize_return_to("/\\evil.com"), "/");
+        assert_eq!(sanitize_return_to("https://evil.com"), "/");
+        assert_eq!(sanitize_return_to("/vote?parent=x"), "/vote?parent=x");
+    }
+}
diff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs
index 5ed535ba199fa736f0048c32623b14c3b1e5de2d..d4a85ef52c15dc35148e4c743f0d646cbbdb056d 100644
--- a/server/src/auth/mod.rs
+++ b/server/src/auth/mod.rs
@@ -26,7 +26,7 @@ use crate::{
     ui_action::UI_RPC_FIELD,
 };
 
-pub use session::{resolve_vote_actor, session_id_from_jar, VoteActor};
+pub use session::{nav_pseudonym, resolve_vote_actor, session_id_from_jar, VoteActor};
 
 pub fn base_url_from_env(port: u16) -> String {
     std::env::var("SORTER2_BASE_URL")
@@ -168,6 +168,10 @@ pub async fn login_page(
         "login · sorter2",
         login_body(session.as_ref(), &aliases, &providers),
         state.views.get_views("/login"),
+        session
+            .as_ref()
+            .filter(|s| !s.pseudonym.trim().is_empty())
+            .map(|s| s.pseudonym.as_str()),
     );
     (jar, Html(markup.into_string())).into_response()
 }
@@ -222,6 +226,7 @@ pub async fn alias_page(
             "choose alias · sorter2",
             body,
             state.views.get_views("/login/alias"),
+            None,
         )
         .into_string(),
     )
@@ -237,7 +242,12 @@ pub async fn github_start(
         .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
     let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref());
     let state_token = session::new_oauth_state();
-    let url = oauth::authorize_url(&cfg, &state_token, query.mock_user.as_deref());
+    let mock_user = if config::mock_oauth_allowed() {
+        query.mock_user.as_deref()
+    } else {
+        None
+    };
+    let url = oauth::authorize_url(&cfg, &state_token, mock_user);
     let jar = jar
         .add(session::oauth_state_cookie_value(&state_token))
         .add(session::auth_return_cookie_value(&return_to));
diff --git a/server/src/auth/session.rs b/server/src/auth/session.rs
index 09659240b9455c6fca12db5652e1d31cf8c2acfc..41df030ded3abcafc0ab3887ab769adf103f9aa0 100644
--- a/server/src/auth/session.rs
+++ b/server/src/auth/session.rs
@@ -5,7 +5,7 @@ use durable::{Db, Durability};
 use rand::Rng;
 
 use crate::{
-    auth::config::AUTH_RETURN_COOKIE,
+    auth::config::{self, AUTH_RETURN_COOKIE},
     fetch::now_ms,
     identity::{DEFAULT_ACTOR_UUID, DEFAULT_PSEUDONYM},
     storage_dto::{SessionDataV1, SESSION_DATA_VERSION},
@@ -37,6 +37,7 @@ pub struct VoteActor {
 }
 
 impl VoteActor {
+    /// Test / bench helper: seed votes as the default pseudonym without a session.
     pub fn anon() -> Self {
         Self {
             pseudonym: DEFAULT_PSEUDONYM.to_string(),
@@ -70,20 +71,51 @@ fn hex_encode(bytes: &[u8]) -> String {
     bytes.iter().map(|b| format!("{b:02x}")).collect()
 }
 
-pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> VoteActor {
-    let Some(session_id) = session_id else {
-        return VoteActor::anon();
-    };
-    let Ok(Some(session)) = load_session(db, session_id) else {
-        return VoteActor::anon();
-    };
-    if session.expires_at <= now_ms() {
-        return VoteActor::anon();
+fn build_cookie(name: &'static str, value: String) -> Cookie<'static> {
+    let mut builder = Cookie::build((name, value))
+        .http_only(true)
+        .same_site(SameSite::Lax)
+        .path("/");
+    if config::cookies_secure() {
+        builder = builder.secure(true);
+    }
+    builder.build()
+}
+
+fn clear_cookie(name: &'static str) -> Cookie<'static> {
+    let mut builder = Cookie::build((name, ""))
+        .http_only(true)
+        .same_site(SameSite::Lax)
+        .path("/")
+        .removal();
+    if config::cookies_secure() {
+        builder = builder.secure(true);
+    }
+    builder.build()
+}
+
+/// Resolve the vote actor from a live session. Fail-closed: never falls back to anon.
+pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> Result<VoteActor, &'static str> {
+    let session_id = session_id.ok_or("sign in to vote")?;
+    let session = load_valid_session(db, session_id).ok_or("session expired")?;
+    if !session_has_pseudonym(&session) {
+        return Err("choose an alias first");
     }
     let trust_weight = user_trust_weight(db, &session.uuid).unwrap_or(1.0);
-    VoteActor {
+    Ok(VoteActor {
         pseudonym: session.current_pseudonym,
         trust_weight,
+    })
+}
+
+/// Display name for the top nav, if any session is active.
+pub fn nav_pseudonym(db: &Db, jar: &CookieJar) -> Option<String> {
+    let sessio

… preview truncated; 10,040 characters omitted

download full diff A

B — 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 B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.