Skip to content

Commit b196bcc

Browse files
committed
app/: checks waiting for review reach GitHub (no null conclusion); check and comment posts hold no transaction; refused posts on /status and the metrics (sc-8900)
1 parent 4e36c55 commit b196bcc

6 files changed

Lines changed: 134 additions & 46 deletions

File tree

‎app/src/forge/checks.rs‎

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,9 @@ pub async fn check_for(build: &Build, project: &Project, org: &Organization) ->
110110
})
111111
}
112112

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

116117
/// Post a CI build's check to its project's forge, and remember the check's ID for the next update.
117118
#[derive(Queueable)]
@@ -128,29 +129,22 @@ pub struct ReportCheck {
128129
)]
129130
impl ReportCheck {
130131
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
132+
use laravel::time::ToSpan;
131133
let build_id = self.build_id;
132-
// 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
133-
// a newer one and leave the forge showing an older state
134-
let posted = laravel::db::transaction(async |_| {
135-
laravel::db::query!("SELECT pg_advisory_xact_lock({LOCKS}, ({build_id} % 2147483647)::int)")
136-
.select()
137-
.await?;
138-
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
139-
if build.mode != "ci" {
140-
return Ok(());
141-
}
142-
let project = Project::find_or_fail(build.project_id).await?;
143-
let Some((target, repository)) = report::target(&project).await? else { return Ok(()) };
144-
let org = Organization::find_or_fail(project.organization_id).await?;
145-
let check = check_for(&build, &project, &org).await?;
146-
let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?;
147-
if build.forge_check_id.as_deref() != Some(id.as_str()) {
148-
laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?;
149-
}
150-
Ok(())
151-
})
152-
.await;
134+
// 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
135+
// newer one and leave the forge showing an older state. The lock is a row in the cache store, taken and
136+
// released in statements of their own (as builds.process's), so the post to the forge runs outside any
137+
// transaction and holds no database connection or lock while it waits for GitHub.
138+
let posted = laravel::cache::lock(&format!("forge.check:{build_id}"), HOLD_SECONDS.seconds())?
139+
.block(10.seconds())
140+
.get(|| post(build_id))
141+
.await;
153142
match posted {
143+
// Another post of this build is still going: try again once it's done
144+
Err(e) if e.is::<laravel::cache::LockTimeout>() => {
145+
attempt.release(10.seconds());
146+
Ok(())
147+
}
154148
Err(e) if e.downcast_ref::<RateLimited>().is_some() => {
155149
let wait = e.downcast_ref::<RateLimited>().map(|r| r.retry_in).unwrap_or_default();
156150
tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the check later");
@@ -165,3 +159,21 @@ impl ReportCheck {
165159
self.build_id
166160
}
167161
}
162+
163+
/// Post the build's check as it is now: read it, post it (no transaction open), then record the check's ID. Run
164+
/// under the build's lock ([`ReportCheck`]).
165+
async fn post(build_id: i64) -> laravel::Result<()> {
166+
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
167+
if build.mode != "ci" {
168+
return Ok(());
169+
}
170+
let project = Project::find_or_fail(build.project_id).await?;
171+
let Some((target, repository)) = report::target(&project).await? else { return Ok(()) };
172+
let org = Organization::find_or_fail(project.organization_id).await?;
173+
let check = check_for(&build, &project, &org).await?;
174+
let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?;
175+
if build.forge_check_id.as_deref() != Some(id.as_str()) {
176+
laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?;
177+
}
178+
Ok(())
179+
}

‎app/src/forge/pr_comment.rs‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,9 @@ pub async fn suites(project: &Project, org: &Organization, pr_number: i32) -> la
262262
Ok(out)
263263
}
264264

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

268269
/// Post or update VisualCI's comment on a CI build's pull request.
269270
#[derive(Queueable)]
@@ -280,22 +281,26 @@ pub struct PostPrComment {
280281
)]
281282
impl PostPrComment {
282283
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
284+
use laravel::time::ToSpan;
283285
let build_id = self.build_id;
284286
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
285287
let Some(pr_number) = build.pr_number.filter(|_| build.mode == "ci") else { return Ok(()) };
286288
let project_id = build.project_id;
287289
// One post at a time per project and pull request (builds of two suites post to the same comment), the
288-
// comment's row read and written under the lock
289-
let posted = db::transaction(async |_| {
290-
db::query!(
291-
"SELECT pg_advisory_xact_lock({LOCKS}, hashtext({project_id}::text || ':' || {pr_number}::text))"
292-
)
293-
.select()
294-
.await?;
295-
post(project_id, pr_number, build_id).await
296-
})
297-
.await;
290+
// comment's row read and written under the lock. The lock is a row in the cache store, taken and released in
291+
// statements of their own, so the posts to the forge run outside any transaction and hold no database
292+
// connection or lock while they wait for GitHub.
293+
let posted =
294+
laravel::cache::lock(&format!("forge.pr_comment:{project_id}:{pr_number}"), HOLD_SECONDS.seconds())?
295+
.block(10.seconds())
296+
.get(|| post(project_id, pr_number, build_id))
297+
.await;
298298
match posted {
299+
// Another post to this pull request is still going: try again once it's done
300+
Err(e) if e.is::<laravel::cache::LockTimeout>() => {
301+
attempt.release(10.seconds());
302+
Ok(())
303+
}
299304
Err(e) if e.downcast_ref::<RateLimited>().is_some() => {
300305
let wait = e.downcast_ref::<RateLimited>().map(|r| r.retry_in).unwrap_or_default();
301306
tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the comment later");

‎app/src/forge/report.rs‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,21 @@ pub fn status_state(check: &Check) -> &'static str {
135135
}
136136
}
137137

138+
/// A check as GitHub's check-run body. `conclusion` is there only when there is one: GitHub refuses `null` ("nil is
139+
/// not a string", a 422), so a check waiting for review (in progress, no conclusion) leaves it out. (3 Dec 2026: every
140+
/// build waiting for review got no check, so pull requests waited for a VisualCI check that never came.)
141+
#[must_use]
142+
pub fn github_check_run(check: &Check) -> Value {
143+
let mut body = json!({
144+
"name": check.name, "head_sha": check.head_sha, "status": check.status, "details_url": check.details_url,
145+
"output": { "title": check.title, "summary": check.summary },
146+
});
147+
if let Some(conclusion) = &check.conclusion {
148+
body["conclusion"] = json!(conclusion);
149+
}
150+
body
151+
}
152+
138153
/// Create or update a check on a commit; returns its ID for the next update (GitLab keeps one status per name and
139154
/// commit, so its "ID" is the status's name).
140155
///
@@ -154,15 +169,9 @@ pub async fn report_check(
154169
Some(id) => client::patch(format!("{GITHUB}/repos/{path}/check-runs/{id}")),
155170
None => client::post(format!("{GITHUB}/repos/{path}/check-runs")),
156171
};
157-
let request = request
158-
.token(token)
159-
.header("accept", "application/vnd.github+json")
160-
.header("user-agent", "visualci")
161-
.json(json!({
162-
"name": check.name, "head_sha": check.head_sha, "status": check.status,
163-
"conclusion": check.conclusion, "details_url": check.details_url,
164-
"output": { "title": check.title, "summary": check.summary },
165-
}));
172+
let request =
173+
request.token(token).header("accept", "application/vnd.github+json").header("user-agent", "visualci");
174+
let request = request.json(github_check_run(check));
166175
let reply = outbound::exchange(request, GITHUB).await?;
167176
if !reply.successful() {
168177
return Err(refused("GitHub check run", &reply));

‎app/src/http/renderer.rs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,11 @@ async fn metrics_text() -> laravel::Result<String> {
333333
(SELECT COUNT(*) FROM renders WHERE state = 'queued')::BIGINT AS queued, \
334334
(SELECT COUNT(*) FROM renders WHERE state = 'rendering')::BIGINT AS rendering, \
335335
(SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \
336-
AS gallery_purges_failed"
336+
AS gallery_purges_failed, \
337+
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
338+
AND payload LIKE '%forge.check%')::BIGINT AS checks_failed, \
339+
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
340+
AND payload LIKE '%forge.pr_comment%')::BIGINT AS comments_failed"
337341
)
338342
.select_one()
339343
.await?
@@ -386,6 +390,13 @@ async fn metrics_text() -> laravel::Result<String> {
386390
"Public gallery purges that used up their retries in the last 7 days.",
387391
&[("", n("gallery_purges_failed"))],
388392
);
393+
// Alerted on any (critical: a pull request waits for a VisualCI check that never comes)
394+
gauge(
395+
&mut out,
396+
"visualci_forge_posts_failed_24h",
397+
"Forge checks and pull request comments refused until they used up their retries, in the last 24 hours.",
398+
&[("{kind=\"check\"}", n("checks_failed")), ("{kind=\"comment\"}", n("comments_failed"))],
399+
);
389400
gauge(
390401
&mut out,
391402
"visualci_renders_now",

‎app/src/http/status.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,10 @@ async fn numbers() -> laravel::Result<Json<Value>> {
4949
AS empty_groups, \
5050
(SELECT COUNT(*) FROM gallery_purge_failures WHERE created_at > now() - interval '7 days')::BIGINT \
5151
AS gallery_purges_failed, \
52+
(SELECT COUNT(*) FROM failed_jobs WHERE failed_at > now() - interval '24 hours' \
53+
AND (payload LIKE '%forge.check%' OR payload LIKE '%forge.pr_comment%'))::BIGINT AS forge_posts_failed, \
54+
(SELECT COUNT(*) FROM jobs WHERE attempts >= 3 \
55+
AND (payload LIKE '%forge.check%' OR payload LIKE '%forge.pr_comment%'))::BIGINT AS forge_posts_retrying, \
5256
COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(synced_at)) FROM memberships \
5357
WHERE source = 'github' AND synced_at IS NOT NULL), 0)::BIGINT AS oldest_forge_sync_seconds"
5458
)
@@ -72,6 +76,12 @@ async fn numbers() -> laravel::Result<Json<Value>> {
7276
"empty_groups": get("empty_groups")?,
7377
// Gallery purges that used up their retries in the last week: Cloudflare may serve stale screenshots.
7478
"gallery_purges_failed": get("gallery_purges_failed")?,
79+
// Checks and pull request comments the forge refused until they used up their retries, in the last day: a pull
80+
// request then waits for a VisualCI check that never comes. Always 0 (3 Dec 2026: GitHub refused every check
81+
// waiting for review for hours, and nothing alerted).
82+
"forge_posts_failed": get("forge_posts_failed")?,
83+
// Posts on their third try or later, still retrying: a refusal that's about to become a failure.
84+
"forge_posts_retrying": get("forge_posts_retrying")?,
7585
// The longest any GitHub-derived membership has gone unchecked: subdomains' hourly forge sync keeps it under an
7686
// hour. With the scheduler down, this, the receiving and processing ages are what still alert.
7787
"oldest_forge_sync_seconds": get("oldest_forge_sync_seconds")?,

‎app/tests/forge_reports.rs‎

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,10 +170,31 @@ async fn linked_build(stats: serde_json::Value) -> laravel::Result<Build> {
170170
Ok(build)
171171
}
172172

173+
/// GitHub's rules for a check run's body (its REST schema): `conclusion`, when there, is one of its values and never
174+
/// null, and a completed check has one. GitHub answers 422 otherwise, as it did to every check waiting for review on
175+
/// 3 Dec 2026 (`"conclusion": null`).
176+
fn github_check_run_problem(body: &serde_json::Value) -> Option<String> {
177+
const CONCLUSIONS: [&str; 7] =
178+
["success", "failure", "neutral", "cancelled", "timed_out", "action_required", "skipped"];
179+
let status = body["status"].as_str().unwrap_or("queued");
180+
match body.get("conclusion") {
181+
Some(serde_json::Value::String(c)) if CONCLUSIONS.contains(&c.as_str()) => None,
182+
Some(other) => Some(format!("For properties/conclusion, {other} is not a member of {CONCLUSIONS:?}")),
183+
None if status == "completed" => Some("a completed check run needs a conclusion".to_string()),
184+
None => None,
185+
}
186+
}
187+
173188
fn github() -> client::HttpFake {
174189
client::fake()
175190
.with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" }))
176-
.with("api.github.com/repos/acme/web/check-runs", json!({ "id": 900 }))
191+
.with("api.github.com/repos/acme/web/check-runs", |request: &client::Request| {
192+
let body: serde_json::Value = request.json().unwrap_or_default();
193+
match github_check_run_problem(&body) {
194+
Some(problem) => client::response().status(422).json(json!({ "message": problem })),
195+
None => client::response().json(json!({ "id": 900 })),
196+
}
197+
})
177198
.with("api.github.com/repos/acme/web/issues/5/comments", json!({ "id": 700 }))
178199
}
179200

@@ -189,6 +210,7 @@ async fn a_changed_build_gets_a_waiting_check_and_a_comment(_app: Application) -
189210
assert_eq!(check["name"], "VisualCI");
190211
assert_eq!(check["head_sha"], "abc123");
191212
assert_eq!(check["status"], "in_progress");
213+
assert!(check.get("conclusion").is_none(), "no conclusion yet, so none sent (GitHub refuses null): {check}");
192214
assert_eq!(check["output"]["title"], "1 changes waiting for review");
193215
assert!(check["output"]["summary"].as_str().unwrap().contains("**To review:**"), "{check}");
194216
let comment = sent.iter().find(|r| r.url().ends_with("/issues/5/comments")).expect("a comment");
@@ -316,3 +338,22 @@ fn the_comments_hash_leaves_out_its_images_signatures() {
316338
assert_eq!(body_hash(a), body_hash(b));
317339
assert_ne!(body_hash(a), body_hash(&a.replace("ab12", "cd34")), "another image is another body");
318340
}
341+
342+
/// A check or comment the forge kept refusing until it used up its retries shows on /status (and the metrics), so it
343+
/// alerts instead of leaving a pull request waiting for a check that never comes (3 Dec 2026).
344+
#[laravel::test]
345+
async fn refused_checks_show_on_the_status(app: Application) -> laravel::Result<()> {
346+
assert_eq!(app.get("/status").await.json()["forge_posts_failed"], 0);
347+
let job = laravel::str::uuid7().to_string();
348+
let payload = r#"{"displayName":"forge.check","data":{"build_id":91}}"#;
349+
db::query!(
350+
"INSERT INTO failed_jobs (job_id, connection, queue, payload, error, failed_at) \
351+
VALUES ({job}, 'database', 'default', {payload}, 'GitHub check run: HTTP 422', now())"
352+
)
353+
.update()
354+
.await?;
355+
let status = app.get("/status").await.json().clone();
356+
assert_eq!(status["forge_posts_failed"], 1, "{status}");
357+
assert_eq!(status["forge_posts_retrying"], 0, "{status}");
358+
Ok(())
359+
}

0 commit comments

Comments
 (0)