You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [075d4d37] Fix OAuth test mocks so Clojure E2E auth flows work again. HttpServer handlers were crashing on query parsing and token POSTs, which broke Playwright login; also read alias/history via real CSS selectors. Co-authored-by: Cursor Side A — unified diff (full patch): diff --git a/test/auth_login.clj b/test/auth_login.clj index 6f2f00d7aa7340e63d1ac465b0a2234cec7a983f..aa63b66ccb2471b710ba3d168d0461252b39fc10 100644 --- a/test/auth_login.clj +++ b/test/auth_login.clj @@ -14,27 +14,27 @@ (defn- type-alias! [pg text] (page/evaluate pg (.replace - "(() => { const i = document.getElementById('alias-input'); const f = document.getElementById('alias-check-form'); if (!i || !f) return; + "(() => { const i = document.getElementById('alias-input'); const f = document.getElementById('alias-check-form'); if (!i || !f) return Promise.resolve('missing-form'); i.value = __TEXT__; const cf = document.getElementById('alias-claim-field'); if (cf) cf.value = i.value; return fetch(f.action, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams(new FormData(f)).toString() }) .then(function (r) { return r.text(); }) - .then(function (t) { eval(t); }); })()" + .then(function (t) { eval(t); return document.getElementById('alias-status')?.textContent || ''; }); })()" "__TEXT__" - (pr-str text))) - (Thread/sleep 400)) + (pr-str text)))) -(defn- element-text [pg test-id] +(defn- element-text [pg selector] (let [raw (page/evaluate pg - (str "document.querySelector('[data-testid=\"" test-id "\"]')?.textContent || ''"))] + (str "document.querySelector(" (pr-str selector) ")?.textContent || ''"))] (when (string? raw) (str/trim raw)))) (defn- wait-for-text [pg test-id text timeout-ms] - (let [deadline (+ (System/currentTimeMillis) timeout-ms)] + (let [deadline (+ (System/currentTimeMillis) timeout-ms) + selector (str "[data-testid=\"" test-id "\"]")] (loop [] - (let [got (or (element-text pg test-id) "")] + (let [got (or (element-text pg selector) "")] (cond (= got text) got (< (System/currentTimeMillis) deadline) (do (Thread/sleep 200) (recur)) diff --git a/test/support/mock_oauth.clj b/test/support/mock_oauth.clj index 5ba7e9be3cf6d2226648e9609a09ed45f306930f..333fe08d56cb06bac2a338cad1c73894d54c4495 100644 --- a/test/support/mock_oauth.clj +++ b/test/support/mock_oauth.clj @@ -7,7 +7,7 @@ (defn- query-param [query key] (when query (some (fn [pair] - (let [[k v] (str/split pair "=" 2)] + (let [[k v] (str/split pair #"=" 2)] (when (= k key) (URLDecoder/decode (or v "") "UTF-8")))) (str/split query #"&")))) @@ -31,11 +31,11 @@ (defn- send-redirect [^HttpExchange ex location] (.set (.getResponseHeaders ex) "Location" location) - (.sendResponseHeaders ex 302 -1) + (.sendResponseHeaders ex 302 0) (.close (.getResponseBody ex))) (defn- read-form [^HttpExchange ex] - (let [body (slurp (.getInputStream ex))] + (let [body (slurp (.getRequestBody ex))] {:code (query-param body "code") :grant (query-param body "grant_type")})) @@ -45,7 +45,7 @@ (str/replace #"^[Bb]earer " ""))) (defn- parse-token-user [token] - (when (str/starts-with? token "mock:") + (when (and token (str/starts-with? token "mock:")) (parse-mock-user (subs token 5)))) (defn- authorize-redirect [exchange query] @@ -55,7 +55,7 @@ user (parse-mock-user mock-user) code (str "mock:" (:id user) ":" (:login user)) loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") - "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + "&state=" (java.net.URLEncoder/encode (or state "") "UTF-8"))] (send-redirect exchange loc))) (defn start-mock-oauth @@ -65,49 +65,56 @@ handler (proxy [HttpHandler] [] (handle [^HttpExchange exchange] - (let [uri (.getRequestURI exchange) - path (.getPath uri) - query (.getQuery uri) - method (.getRequestMethod exchange)] - (cond - ;; GitHub authorize - (str/ends-with? path "/login/oauth/authorize") - (authorize-redirect exchange query) + (try + (let [uri (.getRequestURI exchange) + path (.getPath uri) + query (.getQuery uri) + method (.getRequestMethod exchange)] + (cond + ;; GitHub authorize + (str/ends-with? path "/login/oauth/authorize") + (authorize-redirect exchange query) - ;; Reddit authorize - (str/ends-with? path "/api/v1/authorize") - (authorize-redirect exchange query) + ;; Reddit authorize + (str/ends-with? path "/api/v1/authorize") + (authorize-redirect exchange query) - ;; GitHub token - (and (= method "POST") (str/ends-with? path "/login/oauth/access_token")) - (let [code (or (:code (read-form exchange)) "mock:1002:newbie")] - (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}"))) + ;; GitHub token + (and (= method "POST") (str/ends-with? path "/login/oauth/access_token")) + (let [code (or (:code (read-form exchange)) "mock:1002:newbie")] + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}"))) - ;; Reddit token (client_credentials for import + authorization_code for login) - (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) - (let [form (read-form exchange) - grant (or (:grant form) "") - code (or (:code form) "mock:t2_test:redditor")] - (if (= grant "client_credentials") - (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") - (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) + ;; Reddit token (client_credentials for import + authorization_code for login) + (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) + (let [form (read-form exchange) + grant (or (:grant form) "") + code (or (:code form) "mock:t2_test:redditor")] + (if (= grant "client_credentials") + (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) - ;; GitHub user - (= path "/user") - (let [token (bearer-token exchange) - user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})] - (send-json exchange 200 - (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}"))) + ;; GitHub user + (= path "/user") + (let [token (bearer-token exchange) + user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})] + (send-json exchange 200 + (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}"))) - ;; Reddit /api/v1/me - (str/ends-with? path "/api/v1/me") - (let [token (bearer-token exchange) - user (or (parse-token-user token) {:id "t2_test" :login "redditor"})] - (send-json exchange 200 - (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) + ;; Reddit /api/v1/me + (str/ends-with? path "/api/v1/me") + (let [token (bearer-token exchange) + user (or (parse-token-user token) {:id "t2_test" :login "redditor"})] + (send-json exchange 200 + (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) - :else - (send-json exchange 404 "{\"error\":\"not found\"}")))))] + :else + (send-json exchange 404 "{\"error\":\"not found\"}"))) + (catch Throwable t + (binding [*out* *err*] + (println "mock-oauth handler error:" t)) + (try + (send-json exchange 500 "{\"error\":\"mock-oauth internal\"}") + (catch Throwable _))))))] (.createContext server "/" handler) (.setExecutor server nil) (.start server) diff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj index a630cf0938722193e9af88382d60e777ff371be4..faa27945b6394363914c853627a0bad1e819a5f9 100644 --- a/test/support/mock_reddit.clj +++ b/test/support/mock_reddit.clj @@ -12,7 +12,7 @@ (defn- query-param [query key] (when query (some (fn [pair] - (let [[k v] (str/split pair "=" 2)] + (let [[k v] (str/split pair #"=" 2)] (when (= k key) (URLDecoder/decode (or v "") "UTF-8")))) (str/split query #"&")))) @@ -34,11 +34,11 @@ (defn- send-redirect [^HttpExchange ex location] (.set (.getResponseHeaders ex) "Location" location) - (.sendResponseHeaders ex 302 -1) + (.sendResponseHeaders ex 302 0) (.close (.getResponseBody ex))) (defn- read-form [^HttpExchange ex] - (let [body (slurp (.getInputStream ex))] + (let [body (slurp (.getRequestBody ex))] {:code (query-param body "code") :grant (query-param body "grant_type")})) @@ -48,7 +48,7 @@ (str/replace #"^[Bb]earer " ""))) (defn- parse-token-user [token] - (when (str/starts-with? token "mock:") + (when (and token (str/starts-with? token "mock:")) (parse-mock-user (subs token 5)))) (defn start-mock-reddit @@ -72,7 +72,7 @@ user (parse-mock-user (query-param query "mock_user")) code (str "mock:" (:id user) ":" (:login user)) loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") - "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + "&state=" (java.net.URLEncoder/encode (or state "") "UTF-8"))] (send-redirect exchange loc)) (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) Side B — contributor: tommy-mor Side B — commit message: [1531154d] dequeue -> vec Side B — unified diff (full patch): diff --git a/server/src/projection_apply.rs b/server/src/projection_apply.rs index 9c8990a8af927f35d3344c8d0872a516aba56b86..ad404bacb8bcdd5ae0e682cff97f974fd44528ea 100644 --- a/server/src/projection_apply.rs +++ b/server/src/projection_apply.rs @@ -6,8 +6,6 @@ //! batch as the (non-idempotent) edge merges guarantees exactly-once application //! across replay. -use std::collections::BTreeSet; - use crate::{ event_log::EventLogError, events::{Event, EventRecord}, @@ -44,7 +42,6 @@ pub fn apply_records( let db = projection_store.db(); let mut batch = db.batch(); - let mut vote_parents: BTreeSet = BTreeSet::new(); let mut last_seq = 0u64; for record in records { @@ -70,7 +67,6 @@ pub fn apply_records( *ts, ) .map_err(|e| EventLogError::Apply(e.to_string()))?; - vote_parents.insert(parent); } Event::NodeEnsured { id } => { let parsed = parse_event_id(id)?; @@ -85,11 +81,5 @@ pub fn apply_records( .commit_with(durable::Durability::DisableWal) .map_err(|e| EventLogError::Apply(e.to_string()))?; - for parent in vote_parents { - projection_store - .trim_recent_votes(&parent) - .map_err(|e| EventLogError::Apply(e.to_string()))?; - } - Ok(()) } diff --git a/server/src/projection_store.rs b/server/src/projection_store.rs index 8576d671f351004426207894ac35594ddb0f70cf..9a8953d010029d3639dc3987687554bab8b7663e 100644 --- a/server/src/projection_store.rs +++ b/server/src/projection_store.rs @@ -18,7 +18,7 @@ use crate::{ const PROJECTION_CURSOR_KEY: &str = "cursor"; const PROJECTION_SCHEMA_KEY: &str = "schema_version"; -const PROJECTION_SCHEMA_VERSION: u64 = 3; +const PROJECTION_SCHEMA_VERSION: u64 = 4; #[derive(Debug, thiserror::Error)] pub enum ProjectionStoreError { @@ -142,16 +142,6 @@ impl ProjectionStore { Ok(tree) } - /// Cap a node's recent-vote window after applying votes (best-effort, blind). - pub(crate) fn trim_recent_votes(&self, parent: &ItemId) -> Result<(), ProjectionStoreError> { - node(parent).recent_votes().truncate_back( - &self.db, - crate::storage_schema::RECENT_VOTES_CAP, - Durability::DisableWal, - )?; - Ok(()) - } - /// Cache Reddit display content outside the event log (must be evicted per policy). pub fn put_ephemeral_content( &self, diff --git a/server/src/reducer.rs b/server/src/reducer.rs index 0c75c85150bb9e5f578bbadf58b3e43f8a80be4b..759918b8c0eb8f8bf1ed0911d8877adaa55c8ea6 100644 --- a/server/src/reducer.rs +++ b/server/src/reducer.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{HashMap, HashSet}; use serde::{Deserialize, Serialize}; @@ -52,7 +52,7 @@ pub struct GroupState { pub idx_to_item: Vec, pub edges: HashMap<(usize, usize), f64>, pub voted_pairs: HashSet<(usize, usize)>, - pub recent_votes: VecDeque, + pub recent_votes: Vec, } impl GroupState { @@ -62,7 +62,7 @@ impl GroupState { idx_to_item: Vec::new(), edges: HashMap::new(), voted_pairs: HashSet::new(), - recent_votes: VecDeque::with_capacity(200), + recent_votes: Vec::new(), } } @@ -111,10 +111,7 @@ impl GroupState { self.add_edge_weight(b_idx, a_idx, w_a); self.add_edge_weight(a_idx, b_idx, w_b); - self.recent_votes.push_front(vote); - while self.recent_votes.len() > 200 { - self.recent_votes.pop_back(); - } + self.recent_votes.push(vote); } } diff --git a/server/src/storage_dto.rs b/server/src/storage_dto.rs index 9dfb13c53efe4389277625a6ab3bfc18f566a453..3fd6db5cb909ac4896bd8a3ecace796de5f08781 100644 --- a/server/src/storage_dto.rs +++ b/server/src/storage_dto.rs @@ -39,7 +39,7 @@ pub struct StoredEntityDataV1 { pub link_url: Option, } -/// One vote stored in a node's `recent_votes` deque. +/// One vote stored in a node's `recent_votes` list. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StoredVoteV1 { pub version: u32, diff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs index bd26e665e084b95b10fdfff091c31e8dc84d07b8..5d2bb1d56927fb61c7c6d2d8602bd6882327f862 100644 --- a/server/src/storage_schema.rs +++ b/server/src/storage_schema.rs @@ -2,13 +2,13 @@ //! durable collections instead of one blob per node. //! //! A vote updates a handful of keys: a few edge-weight merges, a voted-pair flag, -//! a recent-vote deque push, and child-link set entries. The in-memory +//! a recent-vote list append, and child-link set entries. The in-memory //! [`crate::reducer::GroupState`] is reconstructed from these keys on read for //! rank-centrality. use std::collections::{BTreeSet, HashMap, HashSet}; -use durable::{Batch, Db, Deque, Durable, Leaf, Map, Sum}; +use durable::{Batch, Db, Durable, Leaf, List, Map, Sum}; use crate::{ path_types::ItemId, @@ -38,8 +38,8 @@ pub struct NodeSchema { pub edges: Map>, /// Voted pairs `(min, max) -> true`. pub voted_pairs: Map>, - /// Recent votes, newest at the front (capped on write). - pub recent_votes: Deque>, + /// Recent votes, append-only oldest-first (cap applied on read). + pub recent_votes: List>, /// When ephemeral Reddit display content was last fetched (ms); absent after eviction. pub fetched_at: Leaf, } @@ -55,7 +55,7 @@ pub struct Store { pub view_meta: Map>, } -/// Cap on the per-node recent-vote window (matches the in-memory reducer). +/// Max recent votes returned when loading a node (query-time cap only). pub const RECENT_VOTES_CAP: u64 = 200; fn id_key(id: &ItemId) -> String { @@ -148,11 +148,14 @@ fn build_group_state( } } - // Deque is front=newest; in-memory VecDeque is also front=newest. - let mut recent_votes = std::collections::VecDeque::new(); - for stored in np.recent_votes().iter(db)? { - recent_votes.push_back(decode_vote(stored).map_err(durable::Error::Deserialize)?); - } + // List is index order (oldest first); keep the newest RECENT_VOTES_CAP entries. + let stored = np.recent_votes().iter(db)?; + let cap = RECENT_VOTES_CAP as usize; + let start = stored.len().saturating_sub(cap); + let recent_votes = stored[start..] + .iter() + .map(|s| decode_vote(s.clone()).map_err(durable::Error::Deserialize)) + .collect::, _>>()?; Ok(GroupState { item_to_idx, @@ -248,7 +251,7 @@ pub fn vote_writes( }; batch.write(pnode.voted_pairs().key(&(lo, hi)).set(&true)); - // Recent votes (newest at front). + // Recent votes (append-only; cap on read). let stored = encode_vote(&VoteData { ts, a: a_id, @@ -260,7 +263,7 @@ pub fn vote_writes( delegate: None, thread_tag: "default".to_string(), }); - batch.push_front(&pnode.recent_votes(), &stored)?; + batch.push(&pnode.recent_votes(), &stored)?; Ok(()) } @@ -314,6 +317,35 @@ mod tests { assert!(load_node_state(&db, &parent).unwrap().is_none()); } + #[test] + fn load_caps_recent_votes_at_query_time() { + let dir = tempfile::tempdir().unwrap(); + let db = Db::open(dir.path()).unwrap(); + let parent = ItemId::root(); + + let mut batch = db.batch(); + for i in 0..RECENT_VOTES_CAP + 10 { + vote_writes(&mut batch, &parent, "alpha", "beta", 1, 0, i as i64).unwrap(); + } + batch.commit().unwrap(); + + assert_eq!( + node(&parent).recent_votes().len(&db).unwrap(), + RECENT_VOTES_CAP + 10 + ); + + let node_state = load_node_state(&db, &parent).unwrap().unwrap(); + assert_eq!(node_state.local_ranking.recent_votes.len(), RECENT_VOTES_CAP as usize); + assert_eq!( + node_state.local_ranking.recent_votes.first().map(|v| v.ts), + Some(10) + ); + assert_eq!( + node_state.local_ranking.recent_votes.last().map(|v| v.ts), + Some(RECENT_VOTES_CAP as i64 + 9) + ); + } + #[test] fn missing_node_is_none() { let dir = tempfile::tempdir().unwrap();