From 17fb5a9ab2496d833e7a8036992476b2b7f03c03 Mon Sep 17 00:00:00 2001 From: kleinbem Date: Sat, 5 Dec 2026 03:10:56 +0000 Subject: [PATCH] fix(db,poll): harden budget ledger, finding events, and revue coverage Address CodeRabbit proactive review findings #689, #690, #691, #692, #693, #694: - Load all spends in the active refill/lookback window instead of capping at 50 rows (#689) - Persist dated refill_samples across budget ledger save/load (#690) - Route poll_repo budget updates through update_budget_ledger so webhook throttle deadlines are not clobbered (#691) - Delete removed provisional spends on save while preserving confirmed spend history (#692) - Run update_finding_status read/update/event insert in a single transaction (#693) - Skip stale apply_revue_coverage updates when blob_sha is absent and newer unreviewed lines exist (#694) --- migrations/0003_refill_samples.sql | 2 + src/db.rs | 178 +++++++++++++------ src/ingest/poll.rs | 130 +++++++++----- tests/db_tests.rs | 271 +++++++++++++++++++++++++++++ 4 files changed, 492 insertions(+), 89 deletions(-) create mode 100644 migrations/0003_refill_samples.sql create mode 100644 tests/db_tests.rs diff --git a/migrations/0003_refill_samples.sql b/migrations/0003_refill_samples.sql new file mode 100644 index 0000000..4d0e4f9 --- /dev/null +++ b/migrations/0003_refill_samples.sql @@ -0,0 +1,2 @@ +-- Persist dated refill window samples so the 7-day rolling maximum survives save/load. +ALTER TABLE budget_state ADD COLUMN refill_samples_json TEXT NOT NULL DEFAULT '[]'; diff --git a/src/db.rs b/src/db.rs index b18acb0..b7d9960 100644 --- a/src/db.rs +++ b/src/db.rs @@ -7,6 +7,7 @@ use jiff::{SignedDuration, Timestamp}; use serde::{Deserialize, Serialize}; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; use sqlx::{FromRow, SqlitePool}; +use std::collections::HashSet; use std::str::FromStr; use std::sync::Arc; use tokio::sync::Mutex; @@ -42,6 +43,8 @@ pub struct BudgetStateRow { pub pool: String, pub limit_per_hour: i64, pub refill_minutes: i64, + #[serde(default)] + pub refill_samples_json: String, pub remaining: i64, pub next_free_at: Option, pub confidence: String, @@ -168,13 +171,11 @@ impl Db { .await?; let full_name = format!("{owner}/{name}"); - sqlx::query( - "INSERT OR IGNORE INTO budget_state (repo, updated_at) VALUES (?1, ?2)", - ) - .bind(&full_name) - .bind(&now) - .execute(&self.pool) - .await?; + sqlx::query("INSERT OR IGNORE INTO budget_state (repo, updated_at) VALUES (?1, ?2)") + .bind(&full_name) + .bind(&now) + .execute(&self.pool) + .await?; Ok(()) } @@ -283,33 +284,57 @@ impl Db { pub async fn load_budget_ledger(&self, repo: &str) -> Result { let state = sqlx::query_as::<_, BudgetStateRow>( - "SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at + "SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at FROM budget_state WHERE repo = ?1", ) .bind(repo) .fetch_optional(&self.pool) .await?; - let spends_rows = sqlx::query_as::<_, SpendRow>( - "SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at - FROM spends WHERE repo = ?1 ORDER BY at DESC LIMIT 50", - ) - .bind(repo) - .fetch_all(&self.pool) - .await?; - let mut ledger = BudgetLedger::default(); + let mut state_updated_at: Option = None; if let Some(s) = state { ledger.limit = u32::try_from(s.limit_per_hour.max(1)).unwrap_or(1); ledger.refill_minutes = u32::try_from(s.refill_minutes.max(60)).unwrap_or(60); + ledger.refill_samples = + serde_json::from_str(&s.refill_samples_json).unwrap_or_default(); ledger.next_free_at = s.next_free_at.as_deref().and_then(|v| v.parse().ok()); ledger.fleet_cooldown_until = s .fleet_cooldown_until .as_deref() .and_then(|v| v.parse().ok()); ledger.confidence = Confidence::parse(&s.confidence); - ledger.last_observed_at = s.updated_at.parse().ok(); + state_updated_at = s.updated_at.parse().ok(); + ledger.last_observed_at = state_updated_at; } + + // Load all spends within the active refill/lookback window (plus any provisional rows), + // with no row cap so repos with limit > 50 never undercount active spends. + let spends_rows = if let Some(updated_at) = state_updated_at { + let anchor = updated_at.min(Timestamp::now()); + // Add 1 minute margin so RFC3339 fractional-second ordering never drops a boundary row. + let lookback_mins = i64::from(ledger.refill_minutes.max(180)) + 1; + let cutoff = (anchor - SignedDuration::from_mins(lookback_mins)).to_string(); + sqlx::query_as::<_, SpendRow>( + "SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at + FROM spends + WHERE repo = ?1 AND (at >= ?2 OR state = 'provisional') + ORDER BY at DESC", + ) + .bind(repo) + .bind(&cutoff) + .fetch_all(&self.pool) + .await? + } else { + sqlx::query_as::<_, SpendRow>( + "SELECT id, repo, identity, at, cause, pr, check_run_id, state, created_at + FROM spends WHERE repo = ?1 ORDER BY at DESC", + ) + .bind(repo) + .fetch_all(&self.pool) + .await? + }; + for sr in spends_rows { if let Ok(at) = sr.at.parse::() { ledger.spends.push(SpendRecord { @@ -329,8 +354,8 @@ impl Db { Ok(ledger) } - /// Serialise load-modify-save of a repo's budget ledger so concurrent webhook deliveries - /// cannot clobber each other's throttle deadlines. + /// Serialise load-modify-save of a repo's budget ledger so concurrent webhook and poll + /// updates cannot clobber each other's throttle deadlines. pub async fn update_budget_ledger( &self, repo: &str, @@ -343,19 +368,37 @@ impl Db { let _guard = self.ledger_lock.lock().await; let mut ledger = self.load_budget_ledger(repo).await?; mutate(&mut ledger); - self.save_budget_ledger(repo, &ledger, now).await?; + self.save_budget_ledger_unlocked(repo, &ledger, now).await?; Ok(ledger) } - pub async fn save_budget_ledger(&self, repo: &str, ledger: &BudgetLedger, now: Timestamp) -> Result<()> { + pub async fn save_budget_ledger( + &self, + repo: &str, + ledger: &BudgetLedger, + now: Timestamp, + ) -> Result<()> { + let _guard = self.ledger_lock.lock().await; + self.save_budget_ledger_unlocked(repo, ledger, now).await + } + + async fn save_budget_ledger_unlocked( + &self, + repo: &str, + ledger: &BudgetLedger, + now: Timestamp, + ) -> Result<()> { let snap = ledger.snapshot(now); let now_str = now.to_string(); + let refill_samples_json = serde_json::to_string(&ledger.refill_samples)?; + let mut tx = self.pool.begin().await?; sqlx::query( - "INSERT INTO budget_state (repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at) - VALUES (?1, 'pooled', ?2, ?3, ?4, ?5, ?6, ?7, ?8) + "INSERT INTO budget_state (repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at) + VALUES (?1, 'pooled', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(repo) DO UPDATE SET limit_per_hour = excluded.limit_per_hour, refill_minutes = excluded.refill_minutes, + refill_samples_json = excluded.refill_samples_json, remaining = excluded.remaining, next_free_at = excluded.next_free_at, confidence = excluded.confidence, @@ -365,30 +408,34 @@ impl Db { .bind(repo) .bind(i64::from(snap.limit)) .bind(i64::from(snap.refill_minutes)) + .bind(&refill_samples_json) .bind(i64::from(snap.remaining)) .bind(snap.next_free_at.map(|t| t.to_string())) .bind(snap.confidence.as_str()) .bind(snap.fleet_cooldown_until.map(|t| t.to_string())) .bind(&now_str) - .execute(&self.pool) + .execute(&mut *tx) .await?; + let mut active_provisional_at: HashSet = HashSet::new(); for sp in &ledger.spends { let at_str = sp.at.to_string(); - let exists: Option<(i64, String)> = sqlx::query_as( - "SELECT id, state FROM spends WHERE repo = ?1 AND at = ?2 LIMIT 1", - ) - .bind(repo) - .bind(&at_str) - .fetch_optional(&self.pool) - .await?; + if sp.state == SpendState::Provisional { + active_provisional_at.insert(at_str.clone()); + } + let exists: Option<(i64, String)> = + sqlx::query_as("SELECT id, state FROM spends WHERE repo = ?1 AND at = ?2 LIMIT 1") + .bind(repo) + .bind(&at_str) + .fetch_optional(&mut *tx) + .await?; match exists { Some((id, cur_state)) if cur_state != sp.state.as_str() => { sqlx::query("UPDATE spends SET state = ?1 WHERE id = ?2") .bind(sp.state.as_str()) .bind(id) - .execute(&self.pool) + .execute(&mut *tx) .await?; } None => { @@ -404,12 +451,30 @@ impl Db { .bind(sp.check_run_id.and_then(|v| i64::try_from(v).ok())) .bind(sp.state.as_str()) .bind(&now_str) - .execute(&self.pool) + .execute(&mut *tx) .await?; } _ => {} } } + + // Remove provisional spends dropped from the ledger (e.g. rate-limited check runs) + // while keeping all confirmed spend history intact. + let stored_provisional: Vec<(i64, String)> = + sqlx::query_as("SELECT id, at FROM spends WHERE repo = ?1 AND state = 'provisional'") + .bind(repo) + .fetch_all(&mut *tx) + .await?; + for (id, at_str) in stored_provisional { + if !active_provisional_at.contains(&at_str) { + sqlx::query("DELETE FROM spends WHERE id = ?1") + .bind(id) + .execute(&mut *tx) + .await?; + } + } + + tx.commit().await?; Ok(()) } @@ -427,7 +492,7 @@ impl Db { pub async fn list_budget_states(&self) -> Result> { let rows = sqlx::query_as::<_, BudgetStateRow>( - "SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at + "SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at FROM budget_state ORDER BY repo", ) .fetch_all(&self.pool) @@ -437,7 +502,7 @@ impl Db { pub async fn get_budget_state(&self, repo: &str) -> Result> { let row = sqlx::query_as::<_, BudgetStateRow>( - "SELECT repo, pool, limit_per_hour, refill_minutes, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at + "SELECT repo, pool, limit_per_hour, refill_minutes, refill_samples_json, remaining, next_free_at, confidence, fleet_cooldown_until, updated_at FROM budget_state WHERE repo = ?1", ) .bind(repo) @@ -636,13 +701,15 @@ impl Db { ) -> Result<()> { let now = now_rfc3339(); if let Some(nb) = not_before { - sqlx::query("UPDATE queue SET state = ?1, not_before = ?2, updated_at = ?3 WHERE id = ?4") - .bind(state) - .bind(nb) - .bind(&now) - .bind(id) - .execute(&self.pool) - .await?; + sqlx::query( + "UPDATE queue SET state = ?1, not_before = ?2, updated_at = ?3 WHERE id = ?4", + ) + .bind(state) + .bind(nb) + .bind(&now) + .bind(id) + .execute(&self.pool) + .await?; } else { sqlx::query("UPDATE queue SET state = ?1, updated_at = ?2 WHERE id = ?3") .bind(state) @@ -720,21 +787,31 @@ impl Db { Ok(rows) } - pub async fn update_finding_status(&self, id: i64, new_status: &str, actor: &str) -> Result { + pub async fn update_finding_status( + &self, + id: i64, + new_status: &str, + actor: &str, + ) -> Result { + let mut tx = self.pool.begin().await?; let current: Option = sqlx::query_scalar("SELECT status FROM findings WHERE id = ?1") .bind(id) - .fetch_optional(&self.pool) + .fetch_optional(&mut *tx) .await?; let Some(from_status) = current else { return Ok(false); }; let now = now_rfc3339(); - sqlx::query("UPDATE findings SET status = ?1 WHERE id = ?2") + let res = sqlx::query("UPDATE findings SET status = ?1 WHERE id = ?2 AND status = ?3") .bind(new_status) .bind(id) - .execute(&self.pool) + .bind(&from_status) + .execute(&mut *tx) .await?; + if res.rows_affected() == 0 { + anyhow::bail!("concurrent status update conflict for finding {id}"); + } sqlx::query( "INSERT INTO finding_events (finding_id, at, from_status, to_status, actor) VALUES (?1, ?2, ?3, ?4, ?5)", @@ -744,8 +821,9 @@ impl Db { .bind(&from_status) .bind(new_status) .bind(actor) - .execute(&self.pool) + .execute(&mut *tx) .await?; + tx.commit().await?; Ok(true) } @@ -986,12 +1064,12 @@ impl Db { .await?; // If an existing row already has a different reviewed_commit and newer unreviewed - // lines, and the incoming report's blob does not match, avoid clearing newer changes. + // lines, and the incoming report's blob is absent or does not match, avoid clearing + // newer changes. if let Some((ref cur_blob, Some(ref cur_commit), unrev)) = existing && cur_commit != commit_sha && unrev > 0 - && blob_sha.is_some() - && cur_blob.as_deref() != blob_sha.as_deref() + && (blob_sha.is_none() || cur_blob.as_deref() != blob_sha.as_deref()) { continue; } diff --git a/src/ingest/poll.rs b/src/ingest/poll.rs index c00b242..84b2c09 100644 --- a/src/ingest/poll.rs +++ b/src/ingest/poll.rs @@ -111,8 +111,9 @@ impl GitHubPoller { return Ok(pem.clone()); } if let Some(path) = &self.config.github_private_key_path { - return std::fs::read_to_string(path) - .with_context(|| format!("failed to read app private key from {}", path.display())); + return std::fs::read_to_string(path).with_context(|| { + format!("failed to read app private key from {}", path.display()) + }); } anyhow::bail!("no GitHub App private key configured") } @@ -255,11 +256,8 @@ impl GitHubPoller { listing_complete = false; break; } - next_url = parse_next_link( - resp.headers() - .get("link") - .and_then(|v| v.to_str().ok()), - ); + next_url = + parse_next_link(resp.headers().get("link").and_then(|v| v.to_str().ok())); let repos: Vec = match resp.json().await { Ok(r) => r, Err(err) => { @@ -338,7 +336,10 @@ impl GitHubPoller { } let tracked = self.db.list_repos().await?; - for repo in tracked.into_iter().filter(|r| r.owner.eq_ignore_ascii_case(&owner)) { + for repo in tracked + .into_iter() + .filter(|r| r.owner.eq_ignore_ascii_case(&owner)) + { let full = format!("{}/{}", repo.owner, repo.name); if let Err(err) = self.poll_repo(&full, &token).await { warn!(repo = full, error = %err, "poll_repo failed"); @@ -362,10 +363,18 @@ impl GitHubPoller { let Some(pulls_val) = self.get_with_etag(&pulls_url, token).await? else { return Ok(()); }; + enum PollLedgerEvent { + CheckRun { + outcome: CheckRunOutcome, + pr: u64, + check_run_id: u64, + author: String, + }, + BotMessage(BotMessage), + } + let pulls: Vec = serde_json::from_value(pulls_val)?; - let mut ledger = self.db.load_budget_ledger(repo).await?; - let now = Timestamp::now(); - let mut changed = false; + let mut events: Vec = Vec::new(); for pr in pulls { let author = pr @@ -400,14 +409,12 @@ impl GitHubPoller { ) .await?; if inserted { - ledger.apply_check_run( - &outcome, - Some(pr.number), - Some(id as u64), - author, - "observed_pr", - ); - changed = true; + events.push(PollLedgerEvent::CheckRun { + outcome, + pr: pr.number, + check_run_id: id as u64, + author: author.to_string(), + }); } } } @@ -440,10 +447,14 @@ impl GitHubPoller { .await?; if inserted { if matches!(msg, BotMessage::Unrecognised { .. }) { - warn!(repo, pr = pr.number, comment_id = id, "unrecognised CodeRabbit comment"); + warn!( + repo, + pr = pr.number, + comment_id = id, + "unrecognised CodeRabbit comment" + ); } - ledger.apply_bot_message(&msg); - changed = true; + events.push(PollLedgerEvent::BotMessage(msg)); } } } @@ -475,17 +486,41 @@ impl GitHubPoller { ) .await?; if inserted { - ledger.apply_bot_message(&msg); - changed = true; + events.push(PollLedgerEvent::BotMessage(msg)); } } } } } - if changed { + if !events.is_empty() { info!(repo, "updated budget ledger from GitHub observations"); - self.db.save_budget_ledger(repo, &ledger, now).await?; + let now = Timestamp::now(); + self.db + .update_budget_ledger(repo, now, |ledger| { + for ev in &events { + match ev { + PollLedgerEvent::CheckRun { + outcome, + pr, + check_run_id, + author, + } => { + ledger.apply_check_run( + outcome, + Some(*pr), + Some(*check_run_id), + author, + "observed_pr", + ); + } + PollLedgerEvent::BotMessage(msg) => { + ledger.apply_bot_message(msg); + } + } + } + }) + .await?; } Ok(()) } @@ -571,7 +606,12 @@ impl GitHubPoller { Ok(out) } - async fn fetch_commit_with_all_files(&self, repo: &str, sha: &str, token: &str) -> Result<(Timestamp, Vec)> { + async fn fetch_commit_with_all_files( + &self, + repo: &str, + sha: &str, + token: &str, + ) -> Result<(Timestamp, Vec)> { let mut next = Some(format!( "{}/repos/{repo}/commits/{sha}?per_page=100", self.config.github_api_base @@ -714,13 +754,16 @@ impl GitHubPoller { } /// Walk new default-branch commits (capped at 20 per poll tick) and update `file_coverage`. - async fn scan_repo_coverage(&self, repo: &str, default_branch: &str, token: &str) -> Result<()> { + async fn scan_repo_coverage( + &self, + repo: &str, + default_branch: &str, + token: &str, + ) -> Result<()> { let cursor = self.db.get_scan_cursor(repo).await?; let existing = self.db.list_file_coverage(repo).await?; - let mut map: HashMap = existing - .into_iter() - .map(|f| (f.path.clone(), f)) - .collect(); + let mut map: HashMap = + existing.into_iter().map(|f| (f.path.clone(), f)).collect(); // First scan: require a complete default-branch tree before advancing any cursor. let initial_tree_blobs: Option> = if cursor.is_none() { @@ -736,7 +779,11 @@ impl GitHubPoller { reviewed_commit: None, by: None, unreviewed_lines: if excluded { 0 } else { 1 }, - unreviewed_since: if excluded { None } else { Some(now_str.clone()) }, + unreviewed_since: if excluded { + None + } else { + Some(now_str.clone()) + }, excluded, }); } @@ -762,7 +809,9 @@ impl GitHubPoller { .into_iter() .rev() .filter_map(|c| { - c.get("sha").and_then(Value::as_str).map(ToString::to_string) + c.get("sha") + .and_then(Value::as_str) + .map(ToString::to_string) }) .collect(); (commits_url, etag, shas) @@ -784,7 +833,9 @@ impl GitHubPoller { arr.iter() .take(20) .filter_map(|c| { - c.get("sha").and_then(Value::as_str).map(ToString::to_string) + c.get("sha") + .and_then(Value::as_str) + .map(ToString::to_string) }) .collect() }) @@ -873,7 +924,10 @@ impl GitHubPoller { let deletions = f.get("deletions").and_then(Value::as_u64).unwrap_or(0); changes.push(CommitFileChange { path: path.to_string(), - blob_sha: f.get("sha").and_then(Value::as_str).map(ToString::to_string), + blob_sha: f + .get("sha") + .and_then(Value::as_str) + .map(ToString::to_string), lines_changed: (additions + deletions) as u32, removed, }); @@ -970,9 +1024,7 @@ impl GitHubPoller { .commit_coverage_batch(repo, &deleted, &upserts, last_sha.as_deref()) .await?; - if completed_all - && let Some(etag) = pending_etag - { + if completed_all && let Some(etag) = pending_etag { self.db.set_etag(&etag_url, &etag).await?; } if let Some(sha) = last_sha { diff --git a/tests/db_tests.rs b/tests/db_tests.rs new file mode 100644 index 0000000..8610f24 --- /dev/null +++ b/tests/db_tests.rs @@ -0,0 +1,271 @@ +use coderabbit_steward::budget::{BudgetLedger, SpendRecord, SpendState}; +use coderabbit_steward::coverage::FileCoverageState; +use coderabbit_steward::db::Db; +use coderabbit_steward::findings::ParsedFinding; +use coderabbit_steward::parse::check_run::CheckRunOutcome; +use coderabbit_steward::parse::comment::BotMessage; +use jiff::{SignedDuration, Timestamp}; + +fn ts(s: &str) -> Timestamp { + s.parse().expect("valid timestamp") +} + +async fn test_db() -> (tempfile::TempDir, Db) { + let dir = tempfile::tempdir().unwrap(); + let db_url = format!( + "sqlite://{}?mode=rwc", + dir.path().join("db.sqlite").display() + ); + let db = Db::connect(&db_url).await.unwrap(); + (dir, db) +} + +#[tokio::test] +async fn budget_load_includes_more_than_50_active_spends() { + let (_dir, db) = test_db().await; + let repo = "kleinbem/high-limit"; + let base = ts("2026-11-22T10:00:00Z"); + + let mut ledger = BudgetLedger { + limit: 60, + ..Default::default() + }; + for i in 0..60 { + ledger.spends.push(SpendRecord { + at: base + SignedDuration::from_secs(i * 30), + state: SpendState::Confirmed, + cause: "observed_pr".to_string(), + identity: "kleinbem".to_string(), + pr: Some(i as u64 + 1), + check_run_id: Some(1000 + i as u64), + }); + } + let now = base + SignedDuration::from_mins(35); + db.save_budget_ledger(repo, &ledger, now).await.unwrap(); + + let loaded = db.load_budget_ledger(repo).await.unwrap(); + let snap = loaded.snapshot(now); + assert_eq!(snap.limit, 60); + assert_eq!(snap.remaining, 0); + assert!(!snap.free); +} + +#[tokio::test] +async fn refill_samples_survive_save_and_load() { + let (_dir, db) = test_db().await; + let repo = "kleinbem/refill-history"; + let t0 = ts("2026-11-22T10:00:00Z"); + + // 1. Confirmed spend at t0, then rate-limited at +10m with 110m wait -> 120m refill sample. + db.update_budget_ledger(repo, t0 + SignedDuration::from_mins(10), |ledger| { + ledger.apply_check_run( + &CheckRunOutcome::Reviewed { + started_at: t0, + completed_at: None, + }, + Some(1), + Some(101), + "kleinbem", + "pr", + ); + ledger.apply_bot_message(&BotMessage::RateLimited { + at: t0 + SignedDuration::from_mins(10), + minutes_until_free: 110, + }); + }) + .await + .unwrap(); + + let after_first = db.load_budget_ledger(repo).await.unwrap(); + assert_eq!(after_first.refill_minutes, 120); + assert_eq!(after_first.refill_samples.len(), 1); + + // 2. Later within 7 days, a 60-minute sample must preserve the 7-day max of 120 minutes. + let t1 = t0 + SignedDuration::from_hours(4); + let after_second = db + .update_budget_ledger(repo, t1 + SignedDuration::from_mins(10), |ledger| { + ledger.apply_check_run( + &CheckRunOutcome::Reviewed { + started_at: t1, + completed_at: None, + }, + Some(2), + Some(102), + "kleinbem", + "pr", + ); + ledger.apply_bot_message(&BotMessage::RateLimited { + at: t1 + SignedDuration::from_mins(10), + minutes_until_free: 50, + }); + }) + .await + .unwrap(); + assert_eq!(after_second.refill_minutes, 120); + + // 3. A lone 60-minute sample with no prior history still produces 60. + let fresh_repo = "kleinbem/fresh-refill"; + let fresh = db + .update_budget_ledger(fresh_repo, t0 + SignedDuration::from_mins(10), |ledger| { + ledger.apply_check_run( + &CheckRunOutcome::Reviewed { + started_at: t0, + completed_at: None, + }, + Some(1), + Some(201), + "kleinbem", + "pr", + ); + ledger.apply_bot_message(&BotMessage::RateLimited { + at: t0 + SignedDuration::from_mins(10), + minutes_until_free: 50, + }); + }) + .await + .unwrap(); + assert_eq!(fresh.refill_minutes, 60); +} + +#[tokio::test] +async fn save_budget_ledger_deletes_removed_provisional_spends_and_keeps_confirmed() { + let (_dir, db) = test_db().await; + let repo = "kleinbem/provisional"; + let t0 = ts("2026-11-22T10:00:00Z"); + let t1 = t0 + SignedDuration::from_mins(5); + + // Seed one confirmed spend and one provisional spend. + db.update_budget_ledger(repo, t1, |ledger| { + ledger.limit = 2; + ledger.apply_check_run( + &CheckRunOutcome::Reviewed { + started_at: t0, + completed_at: None, + }, + Some(1), + Some(10), + "kleinbem", + "pr", + ); + ledger.apply_check_run( + &CheckRunOutcome::InProgress { started_at: t1 }, + Some(2), + Some(20), + "kleinbem", + "pr", + ); + }) + .await + .unwrap(); + + // Rate-limiting check run 20 drops the provisional spend. + db.update_budget_ledger(repo, t1 + SignedDuration::from_mins(1), |ledger| { + ledger.apply_check_run( + &CheckRunOutcome::RateLimited { + started_at: t1, + completed_at: Some(t1 + SignedDuration::from_mins(1)), + }, + Some(2), + Some(20), + "kleinbem", + "pr", + ); + }) + .await + .unwrap(); + + // Reload must NOT restore the removed provisional spend, and must keep the confirmed spend. + let loaded = db.load_budget_ledger(repo).await.unwrap(); + assert_eq!(loaded.spends.len(), 1); + assert_eq!(loaded.spends[0].state, SpendState::Confirmed); + assert_eq!(loaded.spends[0].at, t0); +} + +#[tokio::test] +async fn stale_revue_coverage_without_blob_preserves_unreviewed_lines() { + let (_dir, db) = test_db().await; + let repo = "kleinbem/cov"; + + // Existing row: reviewed at commit_new (blob_new), then modified with 15 unreviewed lines. + db.upsert_file_coverage( + repo, + &FileCoverageState { + path: "src/lib.rs".to_string(), + reviewed_blob: Some("blob_new".to_string()), + reviewed_commit: Some("commit_new".to_string()), + by: Some("coderabbit".to_string()), + unreviewed_lines: 15, + unreviewed_since: Some("2026-11-22T10:00:00Z".to_string()), + excluded: false, + }, + ) + .await + .unwrap(); + + // Stale report for commit_old without a blob_sha must NOT clear unreviewed_lines. + let after = db + .apply_revue_coverage(repo, "commit_old", &[("src/lib.rs".to_string(), None)]) + .await + .unwrap(); + let row = after.iter().find(|f| f.path == "src/lib.rs").unwrap(); + assert_eq!(row.unreviewed_lines, 15); + assert_eq!(row.reviewed_commit.as_deref(), Some("commit_new")); + + // Report for the same commit without a blob_sha still clears unreviewed_lines. + let after_same = db + .apply_revue_coverage(repo, "commit_new", &[("src/lib.rs".to_string(), None)]) + .await + .unwrap(); + let row_same = after_same.iter().find(|f| f.path == "src/lib.rs").unwrap(); + assert_eq!(row_same.unreviewed_lines, 0); + assert_eq!(row_same.by.as_deref(), Some("revue")); +} + +#[tokio::test] +async fn concurrent_finding_status_updates_never_record_stale_from_status() { + let (_dir, db) = test_db().await; + let parsed = ParsedFinding { + path: "src/db.rs".to_string(), + line: Some(10), + severity: "minor".to_string(), + category: "general".to_string(), + title: "Test finding".to_string(), + body: "Body".to_string(), + code_quote: "let x = 1;".to_string(), + }; + let (id, _) = db + .upsert_finding("kleinbem/demo", &parsed, Some("sha1"), None) + .await + .unwrap(); + + let (r1, r2) = tokio::join!( + db.update_finding_status(id, "real", "a1"), + db.update_finding_status(id, "false", "a2"), + ); + + // At least one must succeed; any succeeded transitions must form a valid contiguous chain + // starting from 'new' and ending at the persisted status. + assert!(r1.is_ok() || r2.is_ok()); + + let events: Vec<(String, String)> = sqlx::query_as( + "SELECT from_status, to_status FROM finding_events WHERE finding_id = ?1 ORDER BY id ASC", + ) + .bind(id) + .fetch_all(&db.pool) + .await + .unwrap(); + assert!(!events.is_empty()); + + let mut expected_from = "new".to_string(); + for (from_s, to_s) in &events { + assert_eq!(from_s, &expected_from, "stale from_status in {events:?}"); + expected_from = to_s.clone(); + } + + let final_status: String = sqlx::query_scalar("SELECT status FROM findings WHERE id = ?1") + .bind(id) + .fetch_one(&db.pool) + .await + .unwrap(); + assert_eq!(final_status, expected_from); +}