Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 35 additions & 23 deletions app/src/forge/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,9 @@ pub async fn check_for(build: &Build, project: &Project, org: &Organization) ->
})
}

/// The advisory lock namespace for posting a build's check ("VCI2").
const LOCKS: i32 = 1_447_249_202;
/// How long one post of a build's check may hold the build: GitHub's slowest answer (30 s, `outbound`'s deadline) and
/// then some. A post that dies early releases it at once.
const HOLD_SECONDS: i64 = 120;

/// Post a CI build's check to its project's forge, and remember the check's ID for the next update.
#[derive(Queueable)]
Expand All @@ -128,29 +129,22 @@ pub struct ReportCheck {
)]
impl ReportCheck {
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
use laravel::time::ToSpan;
let build_id = self.build_id;
// One post at a time per build, from the build as it is once the lock is held: a slow post can't land after
// a newer one and leave the forge showing an older state
let posted = laravel::db::transaction(async |_| {
laravel::db::query!("SELECT pg_advisory_xact_lock({LOCKS}, ({build_id} % 2147483647)::int)")
.select()
.await?;
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
if build.mode != "ci" {
return Ok(());
}
let project = Project::find_or_fail(build.project_id).await?;
let Some((target, repository)) = report::target(&project).await? else { return Ok(()) };
let org = Organization::find_or_fail(project.organization_id).await?;
let check = check_for(&build, &project, &org).await?;
let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?;
if build.forge_check_id.as_deref() != Some(id.as_str()) {
laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?;
}
Ok(())
})
.await;
// One post at a time per build, from the build as it is once the lock is held: a slow post can't land after a
// newer one and leave the forge showing an older state. The lock is a row in the cache store, taken and
// released in statements of their own (as builds.process's), so the post to the forge runs outside any
// transaction and holds no database connection or lock while it waits for GitHub.
let posted = laravel::cache::lock(&format!("forge.check:{build_id}"), HOLD_SECONDS.seconds())?
.block(10.seconds())
.get(|| post(build_id))
.await;
match posted {
// Another post of this build is still going: try again once it's done
Err(e) if e.is::<laravel::cache::LockTimeout>() => {
attempt.release(10.seconds());
Ok(())
}
Err(e) if e.downcast_ref::<RateLimited>().is_some() => {
let wait = e.downcast_ref::<RateLimited>().map(|r| r.retry_in).unwrap_or_default();
tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the check later");
Expand All @@ -165,3 +159,21 @@ impl ReportCheck {
self.build_id
}
}

/// Post the build's check as it is now: read it, post it (no transaction open), then record the check's ID. Run
/// under the build's lock ([`ReportCheck`]).
async fn post(build_id: i64) -> laravel::Result<()> {
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
if build.mode != "ci" {
return Ok(());
}
let project = Project::find_or_fail(build.project_id).await?;
let Some((target, repository)) = report::target(&project).await? else { return Ok(()) };
let org = Organization::find_or_fail(project.organization_id).await?;
let check = check_for(&build, &project, &org).await?;
let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?;
if build.forge_check_id.as_deref() != Some(id.as_str()) {
laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?;
}
Ok(())
}
29 changes: 17 additions & 12 deletions app/src/forge/pr_comment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,9 @@ pub async fn suites(project: &Project, org: &Organization, pr_number: i32) -> la
Ok(out)
}

/// The advisory lock namespace for a pull request's comment ("VCI3").
const LOCKS: i32 = 1_447_249_203;
/// How long one post of a pull request's comment may hold it: GitHub's slowest answers (30 s each, `outbound`'s
/// deadline, for a read and a write) and then some. A post that dies early releases it at once.
const HOLD_SECONDS: i64 = 180;

/// Post or update VisualCI's comment on a CI build's pull request.
#[derive(Queueable)]
Expand All @@ -280,22 +281,26 @@ pub struct PostPrComment {
)]
impl PostPrComment {
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
use laravel::time::ToSpan;
let build_id = self.build_id;
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
let Some(pr_number) = build.pr_number.filter(|_| build.mode == "ci") else { return Ok(()) };
let project_id = build.project_id;
// One post at a time per project and pull request (builds of two suites post to the same comment), the
// comment's row read and written under the lock
let posted = db::transaction(async |_| {
db::query!(
"SELECT pg_advisory_xact_lock({LOCKS}, hashtext({project_id}::text || ':' || {pr_number}::text))"
)
.select()
.await?;
post(project_id, pr_number, build_id).await
})
.await;
// comment's row read and written under the lock. The lock is a row in the cache store, taken and released in
// statements of their own, so the posts to the forge run outside any transaction and hold no database
// connection or lock while they wait for GitHub.
let posted =
laravel::cache::lock(&format!("forge.pr_comment:{project_id}:{pr_number}"), HOLD_SECONDS.seconds())?
.block(10.seconds())
.get(|| post(project_id, pr_number, build_id))
.await;
match posted {
// Another post to this pull request is still going: try again once it's done
Err(e) if e.is::<laravel::cache::LockTimeout>() => {
attempt.release(10.seconds());
Ok(())
}
Err(e) if e.downcast_ref::<RateLimited>().is_some() => {
let wait = e.downcast_ref::<RateLimited>().map(|r| r.retry_in).unwrap_or_default();
tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the comment later");
Expand Down
27 changes: 18 additions & 9 deletions app/src/forge/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,21 @@ pub fn status_state(check: &Check) -> &'static str {
}
}

/// A check as GitHub's check-run body. `conclusion` is there only when there is one: GitHub refuses `null` ("nil is
/// not a string", a 422), so a check waiting for review (in progress, no conclusion) leaves it out. (3 Dec 2026: every
/// build waiting for review got no check, so pull requests waited for a VisualCI check that never came.)
#[must_use]
pub fn github_check_run(check: &Check) -> Value {
let mut body = json!({
"name": check.name, "head_sha": check.head_sha, "status": check.status, "details_url": check.details_url,
"output": { "title": check.title, "summary": check.summary },
});
if let Some(conclusion) = &check.conclusion {
body["conclusion"] = json!(conclusion);
}
body
}

/// Create or update a check on a commit; returns its ID for the next update (GitLab keeps one status per name and
/// commit, so its "ID" is the status's name).
///
Expand All @@ -154,15 +169,9 @@ pub async fn report_check(
Some(id) => client::patch(format!("{GITHUB}/repos/{path}/check-runs/{id}")),
None => client::post(format!("{GITHUB}/repos/{path}/check-runs")),
};
let request = request
.token(token)
.header("accept", "application/vnd.github+json")
.header("user-agent", "visualci")
.json(json!({
"name": check.name, "head_sha": check.head_sha, "status": check.status,
"conclusion": check.conclusion, "details_url": check.details_url,
"output": { "title": check.title, "summary": check.summary },
}));
let request =
request.token(token).header("accept", "application/vnd.github+json").header("user-agent", "visualci");
let request = request.json(github_check_run(check));
let reply = outbound::exchange(request, GITHUB).await?;
if !reply.successful() {
return Err(refused("GitHub check run", &reply));
Expand Down
13 changes: 12 additions & 1 deletion app/src/http/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,11 @@ async fn metrics_text() -> laravel::Result<String> {
(SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS queued, \
(SELECT COUNT(*) FROM renders WHERE state = 'rendering')::BIGINT AS rendering, \
(SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \
AS gallery_purges_failed"
AS gallery_purges_failed, \
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
AND payload LIKE '%forge.check%')::BIGINT AS checks_failed, \
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
AND payload LIKE '%forge.pr_comment%')::BIGINT AS comments_failed"
)
.select_one()
.await?
Expand Down Expand Up @@ -386,6 +390,13 @@ async fn metrics_text() -> laravel::Result<String> {
"Public gallery purges that used up their retries in the last 7 days.",
&[("", n("gallery_purges_failed"))],
);
// Alerted on any (critical: a pull request waits for a VisualCI check that never comes)
gauge(
&mut out,
"visualci_forge_posts_failed_24h",
"Forge checks and pull request comments refused until they used up their retries, in the last 24 hours.",
&[("{kind=\"check\"}", n("checks_failed")), ("{kind=\"comment\"}", n("comments_failed"))],
);
gauge(
&mut out,
"visualci_renders_now",
Expand Down
10 changes: 10 additions & 0 deletions app/src/http/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ async fn numbers() -> laravel::Result<Json<Value>> {
AS empty_groups, \
(SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \
AS gallery_purges_failed, \
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
AND (payload LIKE '%forge.check%' OR payload LIKE '%forge.pr_comment%'))::BIGINT AS forge_posts_failed, \
(SELECT COUNT(*) FROM jobs WHERE attempts >= 3 \
AND (payload LIKE '%forge.check%' OR payload LIKE '%forge.pr_comment%'))::BIGINT AS forge_posts_retrying, \
COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \
WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds"
)
Expand All @@ -72,6 +76,12 @@ async fn numbers() -> laravel::Result<Json<Value>> {
"empty_groups": get("empty_groups")?,
// Gallery purges that used up their retries in the last week: Cloudflare may serve stale screenshots.
"gallery_purges_failed": get("gallery_purges_failed")?,
// Checks and pull request comments the forge refused until they used up their retries, in the last day: a pull
// request then waits for a VisualCI check that never comes. Always 0 (3 Dec 2026: GitHub refused every check
// waiting for review for hours, and nothing alerted).
"forge_posts_failed": get("forge_posts_failed")?,
// Posts on their third try or later, still retrying: a refusal that's about to become a failure.
"forge_posts_retrying": get("forge_posts_retrying")?,
// The longest any GitHub-derived membership has gone unchecked: subdomains' hourly forge sync keeps it under an
// hour. With the scheduler down, this, the receiving and processing ages are what still alert.
"oldest_forge_sync_seconds": get("oldest_forge_sync_seconds")?,
Expand Down
43 changes: 42 additions & 1 deletion app/tests/forge_reports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,31 @@ async fn linked_build(stats: serde_json::Value) -> laravel::Result<Build> {
Ok(build)
}

/// GitHub's rules for a check run's body (its REST schema): `conclusion`, when there, is one of its values and never
/// null, and a completed check has one. GitHub answers 422 otherwise, as it did to every check waiting for review on
/// 3 Dec 2026 (`"conclusion": null`).
fn github_check_run_problem(body: &serde_json::Value) -> Option<String> {
const CONCLUSIONS: [&str; 7] =
["success", "failure", "neutral", "cancelled", "timed_out", "action_required", "skipped"];
let status = body["status"].as_str().unwrap_or("queued");
match body.get("conclusion") {
Some(serde_json::Value::String(c)) if CONCLUSIONS.contains(&c.as_str()) => None,
Some(other) => Some(format!("For properties/conclusion, {other} is not a member of {CONCLUSIONS:?}")),
None if status == "completed" => Some("a completed check run needs a conclusion".to_string()),
None => None,
}
}

fn github() -> client::HttpFake {
client::fake()
.with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" }))
.with("api.github.com/repos/acme/web/check-runs", json!({ "id": 900 }))
.with("api.github.com/repos/acme/web/check-runs", |request: &client::Request| {
let body: serde_json::Value = request.json().unwrap_or_default();
match github_check_run_problem(&body) {
Some(problem) => client::response().status(422).json(json!({ "message": problem })),
None => client::response().json(json!({ "id": 900 })),
}
})
.with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 700 }))
}

Expand All @@ -189,6 +210,7 @@ async fn a_changed_build_gets_a_waiting_check_and_a_comment(_app: Application) -
assert_eq!(check["name"], "VisualCI");
assert_eq!(check["head_sha"], "abc123");
assert_eq!(check["status"], "in_progress");
assert!(check.get("conclusion").is_none(), "no conclusion yet, so none sent (GitHub refuses null): {check}");
assert_eq!(check["output"]["title"], "1 changes waiting for review");
assert!(check["output"]["summary"].as_str().unwrap().contains("**To review:**"), "{check}");
let comment = sent.iter().find(|r| r.url().ends_with("/issues/5/comments")).expect("a comment");
Expand Down Expand Up @@ -316,3 +338,22 @@ fn the_comments_hash_leaves_out_its_images_signatures() {
assert_eq!(body_hash(a), body_hash(b));
assert_ne!(body_hash(a), body_hash(&a.replace("ab12", "cd34")), "another image is another body");
}

/// A check or comment the forge kept refusing until it used up its retries shows on /status (and the metrics), so it
/// alerts instead of leaving a pull request waiting for a check that never comes (3 Dec 2026).
#[laravel::test]
async fn refused_checks_show_on_the_status(app: Application) -> laravel::Result<()> {
assert_eq!(app.get("/status").await.json()["forge_posts_failed"], 0);
let job = laravel::str::uuid7().to_string();
let payload = r#"{"displayName":"forge.check","data":{"build_id":91}}"#;
db::query!(
"INSERT INTO failed_jobs (job_id, connection, queue, payload, error, failed_at) \
VALUES ({job}, 'database', 'default', {payload}, 'GitHub check run: HTTP 422', now())"
)
.update()
.await?;
let status = app.get("/status").await.json().clone();
assert_eq!(status["forge_posts_failed"], 1, "{status}");
assert_eq!(status["forge_posts_retrying"], 0, "{status}");
Ok(())
}
Loading