From 0a1ae86972f1e3b23526fda3d0d42b966bb814aa Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:45:26 +0000 Subject: [PATCH 1/3] fix(control): keep recording a session's pull requests until D1 has them A session records each pull request its agent finds in D1's pull_request_sessions, which GitHub's webhooks, review agents' findings and follow-ups find sessions by. It did so once, in the background, as its agent first reported the pull request: a D1 error or a deploy that cut it short left the session listing the pull request while hearing nothing of it, for good, as the hourly sweep looks up only the rows it has. Now the session keeps the pull requests it hasn't recorded (fctl_domain::pulls::Unrecorded) and its alarm records them, trying again a minute later and then as long after as it has tried, up to an hour, for a day. The hourly job records those that sessions of the last two weeks list but D1 doesn't (pull_requests::heal), which also covers a project or workspace that reaches a repository only later, and existing sessions that missed theirs. Either way the session then gets what it would have: its reviews' unsent findings, a lookup, and its agent word of conflicts. --- crates/fctl-control/src/do_session.rs | 117 ++++++-- crates/fctl-control/src/pull_requests.rs | 335 ++++++++++++++++++++++- crates/fctl-domain/src/pulls.rs | 103 ++++++- docs/architecture.md | 23 +- 4 files changed, 550 insertions(+), 28 deletions(-) diff --git a/crates/fctl-control/src/do_session.rs b/crates/fctl-control/src/do_session.rs index 3ff9a8e9b..3600e7edf 100644 --- a/crates/fctl-control/src/do_session.rs +++ b/crates/fctl-control/src/do_session.rs @@ -359,6 +359,11 @@ const HOOKS_READY_AT: &str = "hooks_ready_at"; /// its webhooks (`FINISHED_SETTLE_MS` on), unless it works again first. const HOOKS_FINISHED_AT: &str = "hooks_finished_at"; +/// The pull requests the session lists that D1 may not record as its yet +/// (`fctl_domain::pulls::Unrecorded`, JSON), which its alarm records +/// ([`SessionObject::record_pull_requests`]). +const UNRECORDED: &str = "unrecorded_pull_requests"; + /// Whether `s` is one of the sessions an autopilot started. fn crew(s: &Session) -> bool { s.autopilot @@ -630,6 +635,7 @@ impl DurableObject for SessionObject { self.write_through().await; } self.flush_follow_ups(now_ms()).await; + self.record_pull_requests(now_ms()).await; self.ask_again(now_ms()).await; self.index_now(now_ms()).await; self.expire_images(now_ms()).await; @@ -3242,7 +3248,7 @@ impl SessionObject { self.notify_fleet(&s); } if !found.is_empty() { - self.track_pull_requests(&s, found); + self.track_pull_requests(&s, found, now).await; } let merged_more = merged(&s.pull_requests).len() > merged_before; self.want_done(&s, progress_before, merged_more).await; @@ -3588,31 +3594,100 @@ impl SessionObject { } /// Records the pull requests the session lists from now on, so that - /// GitHub's webhooks about them reach it, passes on the findings their - /// reviews kept since they went to no session (`crate::reviews::listed`), - /// and looks them up where the instance takes the webhook - /// (`crate::pull_requests`), which shows where those findings went. - fn track_pull_requests(&self, s: &Session, prs: Vec) { - let env = self.env.clone(); + /// GitHub's webhooks about them, their reviews' findings and follow-ups + /// reach it: its alarm does, at once, and again until it has + /// ([`Self::record_pull_requests`]). Linear hears of them too, where + /// the session answers it. + async fn track_pull_requests(&self, s: &Session, prs: Vec, now: i64) { + if Self::answers_linear(s) { + let env = self.env.clone(); + let id = s.id.as_str().to_owned(); + let prs = prs.clone(); + self.state.wait_until(async move { + if let Err(e) = crate::delegations::pull_requests(&env, &id, &prs).await { + worker::console_error!( + "telling Linear of the pull requests of {id}: {}", + e.0.message + ); + } + }); + } + let mut unrecorded = self.unrecorded().unwrap_or_default(); + unrecorded.add(prs.into_iter().map(|p| p.url), now); + self.save_unrecorded(&unrecorded); + self.arm(now).await; + } + + /// The pull requests the session lists that D1 may not record yet. + fn unrecorded(&self) -> Option { + serde_json::from_str(&self.meta(UNRECORDED)?).ok() + } + + fn save_unrecorded(&self, u: &fctl_domain::pulls::Unrecorded) { + if let Ok(text) = serde_json::to_string(u) { + self.set_meta(UNRECORDED, &text); + } + } + + /// Records the pull requests the session lists that D1 may not record + /// as its yet ([`UNRECORDED`]), once their time came: those its tokens + /// reach (`crate::pull_requests::track`). Then it passes on the + /// findings their reviews kept since they went to no session + /// (`crate::reviews::listed`), and looks them up where the instance + /// takes the webhook (`crate::pull_requests::refresh`), which shows + /// where those findings went. Sets the alarm for the next try first: + /// a try can fail, or a deploy cut it short. After a day of tries, the + /// hourly job records them (`crate::pull_requests::heal`). + async fn record_pull_requests(&self, now: i64) { + let Some(mut unrecorded) = self.unrecorded() else { + return; + }; + if unrecorded.due > now { + self.arm(unrecorded.due).await; + return; + } + let Some(s) = self.summary() else { return }; let id = s.id.as_str().to_owned(); - let linear = Self::answers_linear(s); + let tried = unrecorded.urls.clone(); + let prs: Vec = s + .pull_requests + .iter() + .filter(|p| tried.iter().any(|u| u.eq_ignore_ascii_case(&p.url))) + .cloned() + .collect(); + if unrecorded.trying(now) { + self.save_unrecorded(&unrecorded); + self.arm(unrecorded.due).await; + } else { + worker::console_error!( + "leaving the pull requests of {id} to the hourly job: recording them failed for a day" + ); + self.delete_meta(UNRECORDED); + } + let Ok(db) = self.env.d1("DB") else { return }; + let tracked = match crate::pull_requests::track(&db, &id, &prs).await { + Ok(t) => t, + Err(e) => { + worker::console_error!("recording the pull requests of {id}: {}", e.0.message); + return; + } + }; + // Those it found meanwhile wait for their own try. + if let Some(mut left) = self.unrecorded() { + if left.recorded(&tried) { + self.delete_meta(UNRECORDED); + } else { + self.save_unrecorded(&left); + } + } + if tracked.is_empty() { + return; + } + let env = self.env.clone(); // Review agents' sessions take no findings. let reviewer = s.review.is_some(); self.state.wait_until(async move { - if linear && let Err(e) = crate::delegations::pull_requests(&env, &id, &prs).await { - worker::console_error!( - "telling Linear of the pull requests of {id}: {}", - e.0.message - ); - } let Ok(db) = env.d1("DB") else { return }; - let tracked = match crate::pull_requests::track(&db, &id, &prs).await { - Ok(t) => t, - Err(e) => { - worker::console_error!("tracking the pull requests of {id}: {}", e.0.message); - return; - } - }; if !reviewer && let Err(e) = crate::reviews::listed(&env, &db, &id, &tracked).await { worker::console_error!( "passing on the unsent review findings of the pull requests of {id}: {}", diff --git a/crates/fctl-control/src/pull_requests.rs b/crates/fctl-control/src/pull_requests.rs index e2d89c0b2..fbe5df04e 100644 --- a/crates/fctl-control/src/pull_requests.rs +++ b/crates/fctl-control/src/pull_requests.rs @@ -45,6 +45,13 @@ const LOOKUP_TIME_MS: i64 = 5 * 60 * 1000; /// How long what GitHub said of a pull request that isn't merged or closed /// stands before the sweep asks again, in case a delivery went missing. const SWEEP_AFTER_MS: i64 = 6 * 60 * 60 * 1000; +/// How far back the hourly job looks for pull requests sessions list that +/// `pull_request_sessions` doesn't record ([`heal`]): sessions created in +/// the last two weeks, which a session's own tries leave them to after a +/// day (`fctl_domain::pulls::RECORD_GIVE_UP_MS`). +const HEAL_WITHIN_MS: i64 = 14 * 24 * 60 * 60 * 1000; +/// Most pull requests [`heal`] records in a run: the next takes the rest. +const HEAL_MAX: i64 = 200; /// The points of an installation's GraphQL rate limit (5,000 an hour or /// more) that lookups of many pull requests leave to its sessions' agents: /// they stop for an account whose installation has fewer left, and the @@ -598,12 +605,21 @@ struct Stale { /// Looks up the pull requests sessions list that aren't merged or closed /// and that nobody looked up for a while: those of sessions from before the -/// webhook, and those whose delivery went missing. From the hourly job. +/// webhook, and those whose delivery went missing. First it records those +/// that sessions list but `pull_request_sessions` doesn't ([`heal`]). From +/// the hourly job. pub async fn sweep(env: &Env, db: &D1Database, now: i64) -> AppResult { let cfg = Config::from_env(env); if !enabled(&cfg) { return Ok(0); } + let healed = match heal(env, &cfg, db, now).await { + Ok(told) => told, + Err(e) => { + worker::console_error!("recording the pull requests sessions list: {}", e.0.message); + 0 + } + }; let stale: Vec = q( db, &format!( @@ -620,7 +636,131 @@ pub async fn sweep(env: &Env, db: &D1Database, now: i64) -> AppResult { .iter() .filter_map(|p| Some((RepoRef::parse(&p.repo)?, u64::try_from(p.number).ok()?))) .collect(); - refresh(env, &cfg, db, &prs, now, false).await + Ok(healed + refresh(env, &cfg, db, &prs, now, false).await?) +} + +/// A pull request a session lists that `pull_request_sessions` doesn't +/// record as the session's ([`unrecorded`]). +#[derive(Deserialize)] +struct Unrecorded { + repo: String, + #[serde(deserialize_with = "int")] + number: i64, + session_id: String, + state: Option, +} + +/// The pull requests that sessions created since `since` list +/// (`sessions.pull_requests`) and `pull_request_sessions` doesn't record +/// as theirs, up to `limit`: those neither merged nor closed, of sessions +/// neither archived nor review agents', that they may be looked up for +/// ([`in_reach`]). A session records those it lists as it finds them +/// (SessionObject's `record_pull_requests`), but a try can fail, a deploy +/// can cut it short, and a project or workspace can reach a repository +/// only later. +async fn unrecorded(db: &D1Database, since: i64, limit: i64) -> AppResult> { + q( + db, + &format!( + "SELECT l.repo AS repo, l.number AS number, l.session_id AS session_id, l.state AS state FROM \ + (SELECT lower(substr(j.url, 20, instr(j.url, '/pull/') - 20)) AS repo, j.number AS number, \ + j.state AS state, j.session_id AS session_id FROM \ + (SELECT s.id AS session_id, json_extract(e.value, '$.url') AS url, \ + json_extract(e.value, '$.number') AS number, json_extract(e.value, '$.state') AS state \ + FROM sessions s, json_each(s.pull_requests) e \ + WHERE s.created_at > ?1 AND s.pull_requests IS NOT NULL AND s.archived = 0 \ + AND NOT EXISTS (SELECT 1 FROM reviews rv WHERE rv.session_id = s.id)) j \ + WHERE j.url LIKE 'https://github.com/%/%/pull/%' AND j.number > 0 \ + AND (j.state IS NULL OR j.state NOT IN ('merged', 'closed'))) l \ + WHERE NOT EXISTS (SELECT 1 FROM pull_request_sessions t \ + WHERE t.repo = l.repo AND t.number = l.number AND t.session_id = l.session_id) \ + AND {} ORDER BY l.session_id, l.repo, l.number LIMIT ?2", + in_reach(None) + ), + &[n(since), n(limit)], + )? + .all() + .await +} + +/// Records the pull requests sessions created since `since` list that +/// `pull_request_sessions` doesn't ([`unrecorded`]), up to `limit`, and +/// returns them: the repository, number and session of each. +async fn record_unrecorded( + db: &D1Database, + since: i64, + limit: i64, +) -> AppResult> { + let missing: Vec<(RepoRef, u64, Unrecorded)> = unrecorded(db, since, limit) + .await? + .into_iter() + .filter_map(|m| Some((RepoRef::parse(&m.repo)?, u64::try_from(m.number).ok()?, m))) + .collect(); + if missing.is_empty() { + return Ok(missing); + } + let statements = missing + .iter() + .map(|(repo, number, m)| { + q( + db, + "INSERT OR IGNORE INTO pull_request_sessions (repo, number, session_id, state) VALUES (?, ?, ?, ?)", + &[ + s(&key(repo)), + n(*number as i64), + s(&m.session_id), + os(m.state.as_deref()), + ], + ) + }) + .collect::>>()?; + crate::db::batch(db, statements).await?; + Ok(missing) +} + +/// Records the pull requests sessions list that `pull_request_sessions` +/// doesn't ([`unrecorded`]), as their sessions would have: passes on the +/// findings their reviews kept since they went to no session +/// (`crate::reviews::listed`), and looks them up, and the agents that +/// opened them hear of their conflicts with their base branches +/// ([`refresh`]). Returns how many times sessions heard. +async fn heal(env: &Env, cfg: &Config, db: &D1Database, now: i64) -> AppResult { + let missing = record_unrecorded(db, now - HEAL_WITHIN_MS, HEAL_MAX).await?; + if missing.is_empty() { + return Ok(0); + } + let mut sessions: BTreeMap<&str, Vec<(RepoRef, u64)>> = BTreeMap::new(); + for (repo, number, m) in &missing { + sessions + .entry(m.session_id.as_str()) + .or_default() + .push((repo.clone(), *number)); + } + worker::console_log!( + "recorded {} pull requests that {} sessions list: {}", + missing.len(), + sessions.len(), + missing + .iter() + .map(|(repo, number, m)| format!("{}#{number} ({})", repo.full_name(), m.session_id)) + .collect::>() + .join(", ") + ); + for (id, prs) in &sessions { + if let Err(e) = crate::reviews::listed(env, db, id, prs).await { + worker::console_error!( + "passing on the unsent review findings of the pull requests of {id}: {}", + e.0.message + ); + } + } + let mut prs: Vec<(RepoRef, u64)> = Vec::new(); + for (repo, number, _) in &missing { + if !prs.iter().any(|(r, x)| x == number && key(r) == key(repo)) { + prs.push((repo.clone(), *number)); + } + } + refresh(env, cfg, db, &prs, now, true).await } /// Asks GitHub again whether pull requests conflict with their base @@ -931,3 +1071,194 @@ async fn tell( } result.is_ok() } + +#[cfg(all(test, target_arch = "wasm32"))] +mod tests { + use super::*; + use crate::testing; + use wasm_bindgen_test::wasm_bindgen_test; + + const NOW: i64 = 1_800_000_000_000; + const HOUR: i64 = 3_600_000; + + /// A pull request as a session lists it, in `sessions.pull_requests`. + fn listed(repo: &str, number: u64, state: &str) -> serde_json::Value { + json!({ + "number": number, + "url": format!("https://github.com/{repo}/pull/{number}"), + "state": state, + }) + } + + /// Acme's workspace, connected to the acme account, with its web + /// project, which writes to acme/api too, and sessions that list pull + /// requests: #1 four (of which D1 records none), #2 one it records + /// already, and the others one each that D1 needn't record. + async fn world(db: &D1Database) -> AppResult<()> { + for sql in [ + "INSERT INTO users (id, email, name, created_at, updated_at) VALUES ('usr_ada', 'ada@example.com', 'Ada', 0, 0)", + "INSERT INTO workspaces (id, slug, name, created_at, updated_at) VALUES ('wsp_acme', 'acme', 'Acme', 0, 0)", + "INSERT INTO workspace_github (workspace_id, account, installation_id, account_id, status, created_at, updated_at) \ + VALUES ('wsp_acme', 'acme', 42, 314, 'active', 0, 0)", + "INSERT INTO projects (id, slug, name, repo_owner, repo_name, created_by, created_at, updated_at, workspace_id) \ + VALUES ('prj_web', 'web', 'Web', 'acme', 'web', 'usr_ada', 0, 0, 'wsp_acme')", + "INSERT INTO project_repos (project_id, owner, name, access, created_at) VALUES ('prj_web', 'acme', 'api', 'write', 0)", + ] { + q(db, sql, &[])?.run().await?; + } + let sessions = [ + // In another case, as GitHub's names don't care; merged; and + // in a repository the workspace doesn't reach. + ( + "ses_1", + NOW - HOUR, + 0, + json!([ + listed("acme/web", 12, "open"), + listed("Acme/API", 7, "draft"), + listed("acme/web", 11, "merged"), + listed("elsewhere/lib", 3, "open"), + ]), + ), + ( + "ses_2", + NOW - HOUR, + 0, + json!([listed("acme/web", 16, "open")]), + ), + // Archived. + ( + "ses_3", + NOW - HOUR, + 1, + json!([listed("acme/web", 13, "open")]), + ), + // From before the two weeks. + ( + "ses_4", + NOW - 20 * 24 * HOUR, + 0, + json!([listed("acme/web", 14, "open")]), + ), + // A review agent's. + ( + "ses_5", + NOW - HOUR, + 0, + json!([listed("acme/web", 15, "open")]), + ), + ]; + for (i, (id, created, archived, prs)) in sessions.iter().enumerate() { + q( + db, + "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, claude_session_id, created_at, updated_at, archived, pull_requests) \ + VALUES (?1, 'prj_web', ?2, 'A change', 'x', 'idle', 'usr_ada', ?1, ?3, ?4, ?5, ?6)", + &[ + s(id), + n(i as i64 + 1), + n(*created), + n(*created), + n(*archived), + s(&prs.to_string()), + ], + )? + .run() + .await?; + } + for sql in [ + "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, claude_session_id, created_at, updated_at) \ + VALUES ('ses_6', 'prj_web', 6, 'Nothing yet', 'x', 'idle', 'usr_ada', 'c6', 1799990000000, 1799990000000)", + "INSERT INTO pull_request_sessions (repo, number, session_id, state) VALUES ('acme/web', 16, 'ses_2', 'open')", + "INSERT INTO reviews (session_id, project_id, repo, repo_key, number, head_sha, url, created_at) \ + VALUES ('ses_5', 'prj_web', 'acme/web', 'acme/web', 15, 'abc', 'https://github.com/acme/web/pull/15', 0)", + ] { + q(db, sql, &[])?.run().await?; + } + Ok(()) + } + + #[derive(Deserialize, Debug, PartialEq)] + struct Row { + repo: String, + #[serde(deserialize_with = "int")] + number: i64, + session_id: String, + state: Option, + } + + async fn rows(db: &D1Database) -> AppResult> { + q( + db, + "SELECT repo, number, session_id, state FROM pull_request_sessions ORDER BY session_id, repo, number", + &[], + )? + .all() + .await + } + + fn row(repo: &str, number: i64, session_id: &str, state: &str) -> Row { + Row { + repo: repo.into(), + number, + session_id: session_id.into(), + state: Some(state.into()), + } + } + + fn named(found: &[(RepoRef, u64, Unrecorded)]) -> Vec { + found + .iter() + .map(|(repo, number, m)| format!("{}#{number} {}", repo.full_name(), m.session_id)) + .collect() + } + + #[wasm_bindgen_test] + async fn the_hourly_job_records_the_pull_requests_sessions_list_that_d1_missed() -> AppResult<()> + { + let db = testing::database(); + world(&db).await?; + let since = NOW - HEAL_WITHIN_MS; + let found = record_unrecorded(&db, since, HEAL_MAX).await?; + assert_eq!(named(&found), ["acme/api#7 ses_1", "acme/web#12 ses_1"]); + assert_eq!( + rows(&db).await?, + [ + row("acme/api", 7, "ses_1", "draft"), + row("acme/web", 12, "ses_1", "open"), + row("acme/web", 16, "ses_2", "open"), + ] + ); + // Once recorded, they are no longer missing. + assert!(record_unrecorded(&db, since, HEAL_MAX).await?.is_empty()); + Ok(()) + } + + #[wasm_bindgen_test] + async fn the_next_run_records_those_one_had_no_room_for() -> AppResult<()> { + let db = testing::database(); + world(&db).await?; + let since = NOW - HEAL_WITHIN_MS; + let first = record_unrecorded(&db, since, 1).await?; + assert_eq!(named(&first), ["acme/api#7 ses_1"]); + let next = record_unrecorded(&db, since, 1).await?; + assert_eq!(named(&next), ["acme/web#12 ses_1"]); + assert!(record_unrecorded(&db, since, 1).await?.is_empty()); + Ok(()) + } + + #[wasm_bindgen_test] + async fn it_records_none_the_workspace_reaches_no_longer() -> AppResult<()> { + let db = testing::database(); + world(&db).await?; + q( + &db, + "DELETE FROM workspace_github WHERE workspace_id = 'wsp_acme'", + &[], + )? + .run() + .await?; + let found = record_unrecorded(&db, NOW - HEAL_WITHIN_MS, HEAL_MAX).await?; + assert!(found.is_empty(), "{:?}", named(&found)); + Ok(()) + } +} diff --git a/crates/fctl-domain/src/pulls.rs b/crates/fctl-domain/src/pulls.rs index 66566f0a7..79e85ac0a 100644 --- a/crates/fctl-domain/src/pulls.rs +++ b/crates/fctl-domain/src/pulls.rs @@ -19,7 +19,7 @@ use fctl_proto::Millis; use fctl_proto::event::GitState; use fctl_proto::session::{PullRequestChecks, PullRequestRef, RepoRef, Session}; -use serde::Serialize; +use serde::{Deserialize, Serialize}; /// Most pull requests a session lists: the first its agent found. pub const MAX_PULL_REQUESTS: usize = 20; @@ -260,6 +260,67 @@ pub fn state_of(merged: bool, closed: bool, queued: bool, draft: bool) -> &'stat } } +/// The shortest wait before a session tries again to record the pull +/// requests it lists ([`Unrecorded`]). +pub const RECORD_AGAIN_FIRST_MS: Millis = 60_000; +/// The longest wait between its tries. +pub const RECORD_AGAIN_MAX_MS: Millis = 60 * 60 * 1000; +/// How long a session tries before it leaves the pull requests it couldn't +/// record to the hourly job, which records those that sessions of the last +/// two weeks list (`crate::pull_requests::heal` in fctl-control). +pub const RECORD_GIVE_UP_MS: Millis = 24 * 60 * 60 * 1000; + +/// Pull requests a session lists that the control plane may not have +/// recorded as the session's yet (`pull_request_sessions` in D1), which +/// GitHub's webhooks, review agents' findings and follow-ups find sessions +/// by: a session that lists one D1 doesn't record hears nothing of it. The +/// session keeps them until a try to record them finishes, and tries again +/// until then, since a try can fail (a D1 error) or be cut short (a deploy +/// resets the session's object). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Unrecorded { + /// Their URLs, as the session lists them. + pub urls: Vec, + /// When the session started trying to record those it still keeps. + pub since: Millis, + /// When it tries next. + pub due: Millis, +} + +impl Unrecorded { + /// Adds pull requests the session lists from now on, `now`: it tries + /// to record them, with any it kept, at once. + pub fn add(&mut self, urls: impl IntoIterator, now: Millis) { + if self.urls.is_empty() { + self.since = now; + } + for url in urls { + if !self.urls.iter().any(|u| same(u, &url)) { + self.urls.push(url); + } + } + self.due = now; + } + + /// Notes a try at `now`, before it starts: should it fail or not + /// finish, the next comes as long after it as the session has tried, + /// from [`RECORD_AGAIN_FIRST_MS`] to [`RECORD_AGAIN_MAX_MS`]. Returns + /// whether there is a next: none once it has tried for + /// [`RECORD_GIVE_UP_MS`]. + pub fn trying(&mut self, now: Millis) -> bool { + let tried = now.saturating_sub(self.since).max(0); + self.due = now + tried.clamp(RECORD_AGAIN_FIRST_MS, RECORD_AGAIN_MAX_MS); + tried < RECORD_GIVE_UP_MS + } + + /// Takes out those a try recorded, `urls`: those added since wait for + /// the next. Returns whether none are left. + pub fn recorded(&mut self, urls: &[String]) -> bool { + self.urls.retain(|u| !urls.iter().any(|r| same(r, u))); + self.urls.is_empty() + } +} + /// Whether a pull request merged or closed, as it was last looked up. pub fn done(pr: &PullRequestRef) -> bool { matches!(pr.state.as_deref(), Some("merged" | "closed")) @@ -1173,4 +1234,44 @@ mod tests { let json = serde_json::to_value(&asks.sessions[0]).unwrap_or_default(); assert!(json.get("archived").is_none()); } + + #[test] + fn a_session_tries_to_record_its_pull_requests_until_one_try_finishes() { + let a = "https://github.com/acme/web/pull/12".to_owned(); + let b = "https://github.com/acme/api/pull/7".to_owned(); + let mut u = Unrecorded::default(); + u.add([a.clone()], 1_000); + assert_eq!((u.since, u.due), (1_000, 1_000)); + // A try that doesn't finish leaves the next a minute on. + assert!(u.trying(1_000)); + assert_eq!(u.due, 61_000); + // Then as long after as it has tried, up to an hour. + assert!(u.trying(61_000)); + assert_eq!(u.due, 121_000); + assert!(u.trying(4 * 3_600_000)); + assert_eq!(u.due, 5 * 3_600_000); + // One it finds meanwhile goes in the next try, at once; the same + // one again, in another case, isn't added twice. + u.add([b.clone(), a.to_uppercase()], 4 * 3_600_000 + 5); + assert_eq!(u.urls, vec![a.clone(), b.clone()]); + assert_eq!((u.since, u.due), (1_000, 4 * 3_600_000 + 5)); + // A try took the first: the second waits for the next. + assert!(!u.recorded(std::slice::from_ref(&a))); + assert_eq!(u.urls, vec![b.clone()]); + assert!(u.recorded(&[b.to_uppercase()])); + // Added once none are left, it starts again. + u.add([a], 9 * 3_600_000); + assert_eq!(u.since, 9 * 3_600_000); + } + + #[test] + fn a_session_leaves_them_to_the_hourly_job_after_a_day() { + let mut u = Unrecorded::default(); + u.add(["https://github.com/acme/web/pull/12".to_owned()], 0); + assert!(u.trying(RECORD_GIVE_UP_MS - 1)); + assert!(!u.trying(RECORD_GIVE_UP_MS)); + // What the session keeps reads as it wrote it. + let json = serde_json::to_string(&u).unwrap_or_default(); + assert_eq!(serde_json::from_str::(&json).ok(), Some(u)); + } } diff --git a/docs/architecture.md b/docs/architecture.md index 7777568c6..81530a5da 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2324,8 +2324,22 @@ session that stopped looks up nothing, so GitHub tells the control plane instance takes none and sessions show what their agents last looked up. 2. **Which sessions.** D1 keeps which sessions list which pull request (`pull_request_sessions`), by repository and number, with its head - commit, which commit statuses name instead of a pull request. SessionDO - adds a session's rows as its agent finds pull requests. + commit, which commit statuses name instead of a pull request. A session + without its row hears nothing of the pull request: no checks or state, + no review findings, no follow-ups. SessionDO adds a session's rows as + its agent finds pull requests, from its alarm: it keeps those it hasn't + recorded yet (`fctl_domain::pulls::Unrecorded`) and tries again, a + minute later and then as long after as it has tried, up to an hour, + since a D1 error can fail a try and a deploy cut one short. After a day + it leaves them to the hourly job, which records those that sessions + created in the last two weeks list (`sessions.pull_requests`) but + `pull_request_sessions` doesn't, neither merged nor closed, of sessions + neither archived nor review agents' (`pull_requests::heal`): that also + covers a project or a workspace that reaches a repository only after + its agent opened a pull request there. Either way, the session then + gets what it would have got as its agent found them: the findings their + reviews kept since they went to no session, a lookup, and, where its + project follows up on conflicts, word of those to its agent. 3. **A lookup.** For the pull requests sessions list that a delivery concerns, the control plane asks GitHub with one GraphQL query (`fctl_domain::webhooks::query`, with a token of the installation that @@ -2659,8 +2673,9 @@ posts what it found on GitHub pull request meanwhile finds it, and whoever sends it claims it first, so that it goes once, and keeps it again if that session takes none. When a session of the review's workspace first lists a pull request - (SessionObject, as it applies a `git` event, `crate::reviews::listed`), - before the pull request is looked up, the findings of its newest review + (SessionObject, once it records the pull request as the session's, or + the hourly job, once it records one the session missed: + `crate::reviews::listed`), before the pull request is looked up, the findings of its newest review that posted go to the session that opened it, as above, if they went to no session and the pull request isn't merged or closed (`fctl_domain::reviews::owed`). A newer review that posted takes the From df2efcd0c8e894c1f47b2f17e609517da85dc6d9 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 00:55:10 +0000 Subject: [PATCH 2/3] fix(control): pass on review findings before a pull request counts as recorded From the review of #681: a session cleared what it hadn't recorded as soon as the rows were in D1, though passing on its reviews' findings came after, and nothing passed those on once the rows were there. It now counts a try once both are done; a lookup that fails is left to the hourly job, which looks up first the rows nobody has. The hourly job also went by when sessions were created, so an older session that found a pull request today, and couldn't record it for a day, got no repair: it now goes by when sessions last changed. --- crates/fctl-control/src/do_session.rs | 37 +++++++++------- crates/fctl-control/src/pull_requests.rs | 55 +++++++++++++++++------- crates/fctl-domain/src/pulls.rs | 4 +- docs/architecture.md | 2 +- 4 files changed, 64 insertions(+), 34 deletions(-) diff --git a/crates/fctl-control/src/do_session.rs b/crates/fctl-control/src/do_session.rs index 3600e7edf..ffcf2eb00 100644 --- a/crates/fctl-control/src/do_session.rs +++ b/crates/fctl-control/src/do_session.rs @@ -3631,13 +3631,14 @@ impl SessionObject { /// Records the pull requests the session lists that D1 may not record /// as its yet ([`UNRECORDED`]), once their time came: those its tokens - /// reach (`crate::pull_requests::track`). Then it passes on the - /// findings their reviews kept since they went to no session - /// (`crate::reviews::listed`), and looks them up where the instance - /// takes the webhook (`crate::pull_requests::refresh`), which shows - /// where those findings went. Sets the alarm for the next try first: - /// a try can fail, or a deploy cut it short. After a day of tries, the - /// hourly job records them (`crate::pull_requests::heal`). + /// reach (`crate::pull_requests::track`), and passes on the findings + /// their reviews kept since they went to no session + /// (`crate::reviews::listed`). A try counts once both are done. Then + /// it looks them up where the instance takes the webhook + /// (`crate::pull_requests::refresh`), which shows where those findings + /// went. Sets the alarm for the next try first: a try can fail, or a + /// deploy cut it short. After a day of tries, the hourly job records + /// them (`crate::pull_requests::heal`). async fn record_pull_requests(&self, now: i64) { let Some(mut unrecorded) = self.unrecorded() else { return; @@ -3672,6 +3673,18 @@ impl SessionObject { return; } }; + // Their reviews' findings before they count as recorded: once + // their rows are in D1, nothing else passes those on. Review + // agents' sessions take none. + if s.review.is_none() + && let Err(e) = crate::reviews::listed(&self.env, &db, &id, &tracked).await + { + worker::console_error!( + "passing on the unsent review findings of the pull requests of {id}: {}", + e.0.message + ); + return; + } // Those it found meanwhile wait for their own try. if let Some(mut left) = self.unrecorded() { if left.recorded(&tried) { @@ -3683,17 +3696,11 @@ impl SessionObject { if tracked.is_empty() { return; } + // A lookup that fails leaves them to the hourly job, which looks up + // first those nobody has. let env = self.env.clone(); - // Review agents' sessions take no findings. - let reviewer = s.review.is_some(); self.state.wait_until(async move { let Ok(db) = env.d1("DB") else { return }; - if !reviewer && let Err(e) = crate::reviews::listed(&env, &db, &id, &tracked).await { - worker::console_error!( - "passing on the unsent review findings of the pull requests of {id}: {}", - e.0.message - ); - } let cfg = crate::config::Config::from_env(&env); if crate::pull_requests::enabled(&cfg) && let Err(e) = diff --git a/crates/fctl-control/src/pull_requests.rs b/crates/fctl-control/src/pull_requests.rs index fbe5df04e..da4a798c2 100644 --- a/crates/fctl-control/src/pull_requests.rs +++ b/crates/fctl-control/src/pull_requests.rs @@ -46,9 +46,9 @@ const LOOKUP_TIME_MS: i64 = 5 * 60 * 1000; /// stands before the sweep asks again, in case a delivery went missing. const SWEEP_AFTER_MS: i64 = 6 * 60 * 60 * 1000; /// How far back the hourly job looks for pull requests sessions list that -/// `pull_request_sessions` doesn't record ([`heal`]): sessions created in -/// the last two weeks, which a session's own tries leave them to after a -/// day (`fctl_domain::pulls::RECORD_GIVE_UP_MS`). +/// `pull_request_sessions` doesn't record ([`heal`]): sessions active in +/// the last two weeks, whose own tries leave them to it after a day +/// (`fctl_domain::pulls::RECORD_GIVE_UP_MS`), however old the session. const HEAL_WITHIN_MS: i64 = 14 * 24 * 60 * 60 * 1000; /// Most pull requests [`heal`] records in a run: the next takes the rest. const HEAL_MAX: i64 = 200; @@ -650,7 +650,8 @@ struct Unrecorded { state: Option, } -/// The pull requests that sessions created since `since` list +/// The pull requests that sessions active since `since` (their +/// `updated_at`, which every change to them moves) list /// (`sessions.pull_requests`) and `pull_request_sessions` doesn't record /// as theirs, up to `limit`: those neither merged nor closed, of sessions /// neither archived nor review agents', that they may be looked up for @@ -668,7 +669,7 @@ async fn unrecorded(db: &D1Database, since: i64, limit: i64) -> AppResult ?1 AND s.pull_requests IS NOT NULL AND s.archived = 0 \ + WHERE s.updated_at > ?1 AND s.pull_requests IS NOT NULL AND s.archived = 0 \ AND NOT EXISTS (SELECT 1 FROM reviews rv WHERE rv.session_id = s.id)) j \ WHERE j.url LIKE 'https://github.com/%/%/pull/%' AND j.number > 0 \ AND (j.state IS NULL OR j.state NOT IN ('merged', 'closed'))) l \ @@ -683,7 +684,7 @@ async fn unrecorded(db: &D1Database, since: i64, limit: i64) -> AppResult AppResult<()> { for sql in [ "INSERT INTO users (id, email, name, created_at, updated_at) VALUES ('usr_ada', 'ada@example.com', 'Ada', 0, 0)", @@ -1106,12 +1108,15 @@ mod tests { ] { q(db, sql, &[])?.run().await?; } + let hour_ago = NOW - HOUR; + // Each with when it was created and last changed. let sessions = [ // In another case, as GitHub's names don't care; merged; and // in a repository the workspace doesn't reach. ( "ses_1", - NOW - HOUR, + hour_ago, + hour_ago, 0, json!([ listed("acme/web", 12, "open"), @@ -1122,33 +1127,45 @@ mod tests { ), ( "ses_2", - NOW - HOUR, + hour_ago, + hour_ago, 0, json!([listed("acme/web", 16, "open")]), ), // Archived. ( "ses_3", - NOW - HOUR, + hour_ago, + hour_ago, 1, json!([listed("acme/web", 13, "open")]), ), - // From before the two weeks. + // Quiet since before the two weeks. ( "ses_4", NOW - 20 * 24 * HOUR, + NOW - 20 * 24 * HOUR, 0, json!([listed("acme/web", 14, "open")]), ), // A review agent's. ( "ses_5", - NOW - HOUR, + hour_ago, + hour_ago, 0, json!([listed("acme/web", 15, "open")]), ), + // A month old, it found one today. + ( + "ses_7", + NOW - 30 * 24 * HOUR, + hour_ago, + 0, + json!([listed("acme/web", 17, "open")]), + ), ]; - for (i, (id, created, archived, prs)) in sessions.iter().enumerate() { + for (i, (id, created, changed, archived, prs)) in sessions.iter().enumerate() { q( db, "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, claude_session_id, created_at, updated_at, archived, pull_requests) \ @@ -1157,7 +1174,7 @@ mod tests { s(id), n(i as i64 + 1), n(*created), - n(*created), + n(*changed), n(*archived), s(&prs.to_string()), ], @@ -1167,7 +1184,7 @@ mod tests { } for sql in [ "INSERT INTO sessions (id, project_id, number, title, prompt, status, created_by, claude_session_id, created_at, updated_at) \ - VALUES ('ses_6', 'prj_web', 6, 'Nothing yet', 'x', 'idle', 'usr_ada', 'c6', 1799990000000, 1799990000000)", + VALUES ('ses_6', 'prj_web', 60, 'Nothing yet', 'x', 'idle', 'usr_ada', 'c6', 1799990000000, 1799990000000)", "INSERT INTO pull_request_sessions (repo, number, session_id, state) VALUES ('acme/web', 16, 'ses_2', 'open')", "INSERT INTO reviews (session_id, project_id, repo, repo_key, number, head_sha, url, created_at) \ VALUES ('ses_5', 'prj_web', 'acme/web', 'acme/web', 15, 'abc', 'https://github.com/acme/web/pull/15', 0)", @@ -1219,13 +1236,17 @@ mod tests { world(&db).await?; let since = NOW - HEAL_WITHIN_MS; let found = record_unrecorded(&db, since, HEAL_MAX).await?; - assert_eq!(named(&found), ["acme/api#7 ses_1", "acme/web#12 ses_1"]); + assert_eq!( + named(&found), + ["acme/api#7 ses_1", "acme/web#12 ses_1", "acme/web#17 ses_7"] + ); assert_eq!( rows(&db).await?, [ row("acme/api", 7, "ses_1", "draft"), row("acme/web", 12, "ses_1", "open"), row("acme/web", 16, "ses_2", "open"), + row("acme/web", 17, "ses_7", "open"), ] ); // Once recorded, they are no longer missing. @@ -1242,6 +1263,8 @@ mod tests { assert_eq!(named(&first), ["acme/api#7 ses_1"]); let next = record_unrecorded(&db, since, 1).await?; assert_eq!(named(&next), ["acme/web#12 ses_1"]); + let last = record_unrecorded(&db, since, 1).await?; + assert_eq!(named(&last), ["acme/web#17 ses_7"]); assert!(record_unrecorded(&db, since, 1).await?.is_empty()); Ok(()) } diff --git a/crates/fctl-domain/src/pulls.rs b/crates/fctl-domain/src/pulls.rs index 79e85ac0a..eb384a5bf 100644 --- a/crates/fctl-domain/src/pulls.rs +++ b/crates/fctl-domain/src/pulls.rs @@ -266,8 +266,8 @@ pub const RECORD_AGAIN_FIRST_MS: Millis = 60_000; /// The longest wait between its tries. pub const RECORD_AGAIN_MAX_MS: Millis = 60 * 60 * 1000; /// How long a session tries before it leaves the pull requests it couldn't -/// record to the hourly job, which records those that sessions of the last -/// two weeks list (`crate::pull_requests::heal` in fctl-control). +/// record to the hourly job, which records those that sessions active in +/// the last two weeks list (`crate::pull_requests::heal` in fctl-control). pub const RECORD_GIVE_UP_MS: Millis = 24 * 60 * 60 * 1000; /// Pull requests a session lists that the control plane may not have diff --git a/docs/architecture.md b/docs/architecture.md index 81530a5da..8f29e77a7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2332,7 +2332,7 @@ session that stopped looks up nothing, so GitHub tells the control plane minute later and then as long after as it has tried, up to an hour, since a D1 error can fail a try and a deploy cut one short. After a day it leaves them to the hourly job, which records those that sessions - created in the last two weeks list (`sessions.pull_requests`) but + active in the last two weeks list (`sessions.pull_requests`) but `pull_request_sessions` doesn't, neither merged nor closed, of sessions neither archived nor review agents' (`pull_requests::heal`): that also covers a project or a workspace that reaches a repository only after From 687f1188895876d6179b37cac83b401acb16673b Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:07:12 +0000 Subject: [PATCH 3/3] fix(control): try again when a listed pull request's findings fail to send From the review of #681: reviews::listed logged a send that failed and returned Ok, so the session counted its pull requests recorded and never sent those findings. It now tries every review and then returns the first error, and the session tries again; findings that went meanwhile don't go twice, as sending claims them first. --- crates/fctl-control/src/pull_requests.rs | 5 ++++- crates/fctl-control/src/reviews.rs | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/fctl-control/src/pull_requests.rs b/crates/fctl-control/src/pull_requests.rs index da4a798c2..be5f7eb08 100644 --- a/crates/fctl-control/src/pull_requests.rs +++ b/crates/fctl-control/src/pull_requests.rs @@ -724,7 +724,10 @@ async fn record_unrecorded( /// findings their reviews kept since they went to no session /// (`crate::reviews::listed`), and looks them up, and the agents that /// opened them hear of their conflicts with their base branches -/// ([`refresh`]). Returns how many times sessions heard. +/// ([`refresh`]). Findings it couldn't pass on stay with their reviews, +/// which the session's page then offers to pass on, as the lookup shows +/// them unsent (`ReviewCheck::unsent`). Returns how many times sessions +/// heard. async fn heal(env: &Env, cfg: &Config, db: &D1Database, now: i64) -> AppResult { let missing = record_unrecorded(db, now - HEAL_WITHIN_MS, HEAL_MAX).await?; if missing.is_empty() { diff --git a/crates/fctl-control/src/reviews.rs b/crates/fctl-control/src/reviews.rs index 76c1a23e2..5f4b68f67 100644 --- a/crates/fctl-control/src/reviews.rs +++ b/crates/fctl-control/src/reviews.rs @@ -2578,7 +2578,9 @@ async fn audit( /// pull request still owes them, as when the review posted ([`send`]). A /// session whose turn was cut short before its agent reported the pull /// request it opened gets them once it does. Returns how many reviews' -/// findings went to a session. +/// findings went to a session, or, once it has tried them all, the first +/// error of one it couldn't send: the caller tries again later, and those +/// that went meanwhile don't go twice ([`claim`]). pub async fn listed( env: &Env, db: &D1Database, @@ -2595,6 +2597,7 @@ pub async fn listed( return Ok(0); }; let mut sent = 0; + let mut failed = None; for (repo, number) in prs { let key = crate::pull_requests::key(repo); let Some(state) = listing(db, &key, *number, session_id).await? else { @@ -2616,14 +2619,20 @@ pub async fn listed( sent += 1; } Ok(Sent::Held | Sent::Nowhere) => {} - Err(e) => worker::console_error!( - "passing review {}'s unsent findings on: {}", - row.session_id, - e.0.message - ), + Err(e) => { + worker::console_error!( + "passing review {}'s unsent findings on: {}", + row.session_id, + e.0.message + ); + failed.get_or_insert(e); + } } } - Ok(sent) + match failed { + Some(e) => Err(e), + None => Ok(sent), + } } /// Whether session `session_id` lists pull request `number` of repository