Skip to content
1 change: 1 addition & 0 deletions oxa/oxa-cli/src/work_board/landing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ pub(super) fn review_decisions(
LandingDecision {
next: plan.next,
queue_alarm: plan.queue_alarm,
repeat_rejection_alarm: false,
queue: queued.remove(&number),
latest_reviews: observations[&number].reviews,
would_notify_rejection: None,
Expand Down
113 changes: 107 additions & 6 deletions oxa/oxa-work/src/board/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub mod report;
const BATCH: usize = 8;
const MAX_PRS: usize = 1000;
const MAX_BYTES: usize = 4 * 1024 * 1024;
const QUEUE: &str = r#"mergeQueue(branch:"main"){id}"#;
const QUEUE: &str = r#"id mergeQueue(branch:"main"){id}"#;

#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub struct RejectionEvidence {
Expand All @@ -18,6 +18,8 @@ pub struct RejectionEvidence {
removed_at: String,
#[serde(skip)]
notification_target: Option<NotificationTarget>,
#[serde(skip)]
publication: Option<PublicationBinding>,
merge_group_head: String,
failed_required_check_runs: Vec<u64>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
Expand All @@ -28,9 +30,18 @@ pub struct RejectionEvidence {

#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
pub(crate) struct NotificationTarget {
pull_request_id: String,
author_id: String,
login: String,
pub(crate) pull_request_id: String,
pub(crate) author_id: String,
pub(crate) login: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct PublicationBinding {
repository_id: String,
queue_id: String,
pr_head: String,
absent: bool,
admission_upper_bound: Option<u8>,
}

impl NotificationTarget {
Expand Down Expand Up @@ -77,6 +88,24 @@ impl RejectionEvidence {
self.notification_target.as_ref()
}

pub(crate) fn publication_binding(&self) -> Option<(crate::RejectedLanding, Option<u8>)> {
let binding = self.publication.as_ref()?;
let target = self.notification_target()?;
Some((
crate::RejectedLanding {
repository_id: binding.repository_id.clone(),
queue_id: binding.queue_id.clone(),
pull_request_id: target.pull_request_id.clone(),
pull_request_number: self.number,
pr_head: binding.pr_head.clone(),
rejected_group: self.merge_group_head.clone(),
removal_id: self.removal_event.clone(),
removed_at: oxa_session::parse_utc_seconds(&self.removed_at)?,
},
binding.admission_upper_bound.filter(|_| binding.absent),
))
}

pub(crate) fn admission_identity(&self) -> Removal<'_> {
Removal {
number: self.number,
Expand Down Expand Up @@ -147,6 +176,10 @@ pub fn read(
fields,
r#"p{n}:pullRequest(number:{n}){{
id number headRefOid state baseRefName
mergeQueueEntry{{id}}
admissions:timelineItems(last:3,itemTypes:[ADDED_TO_MERGE_QUEUE_EVENT]){{
pageInfo{{hasPreviousPage hasNextPage}} nodes{{__typename ... on AddedToMergeQueueEvent{{id}}}}
}}
author{{__typename login ... on User{{id}} ... on Bot{{id}}}}
timelineItems(last:1,itemTypes:[ADDED_TO_MERGE_QUEUE_EVENT,REMOVED_FROM_MERGE_QUEUE_EVENT]){{
nodes{{__typename ... on RemovedFromMergeQueueEvent{{
Expand Down Expand Up @@ -182,14 +215,46 @@ pub fn read(
}
let Some(queue_id) = current else { continue };
for entry in batch {
if let Some(rejection) = rejection(&data[format!("p{}", entry.number)], entry, queue_id)? {
if let Some(rejection) = rejection(
&data[format!("p{}", entry.number)],
entry,
queue_id,
node_id(&data["id"]),
)? {
rejections.push(rejection);
}
}
}
Ok(rejections)
}

/// Re-read the exact pending entry using the same repository Reader.
pub fn read_acknowledged_admission(
acknowledgment: &crate::AdmissionAcknowledgment,
mut repository_read: impl FnMut(&str) -> Result<(Value, usize), String>,
) -> Result<Value, String> {
let rejection = &acknowledgment.intent.delivery.intent.rejection;
let number = rejection.pull_request_number;
let (data, bytes) = repository_read(&format!(
r#"id mergeQueue(branch:"main"){{id}} pullRequest(number:{number}){{
mergeQueueEntry{{id enqueuedAt mergeQueue{{id repository{{id}}}}
pullRequest{{id number headRefOid}} headCommit{{oid}}
enqueuer{{__typename ... on User{{id}} ... on Bot{{id}}}}}}
}}"#
))?;
if bytes > MAX_BYTES
|| data["id"].as_str() != Some(&rejection.repository_id)
|| data["mergeQueue"]["id"].as_str() != Some(&rejection.queue_id)
{
return Err("queue changed since the recorded admission acknowledgment".into());
}
data["pullRequest"]["mergeQueueEntry"]
.as_object()
.cloned()
.map(Value::Object)
.ok_or_else(|| "the acknowledged queue entry is unavailable".into())
}

fn node_id(value: &Value) -> Option<&str> {
value.as_str().filter(|id| is_node_id(id))
}
Expand All @@ -209,7 +274,12 @@ pub fn is_object_id(sha: &str) -> bool {
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

fn rejection(row: &Value, entry: &Entry, queue_id: &str) -> Result<Option<RejectionEvidence>, String> {
fn rejection(
row: &Value,
entry: &Entry,
queue_id: &str,
repository_id: Option<&str>,
) -> Result<Option<RejectionEvidence>, String> {
if row["number"].as_u64() != Some(entry.number)
|| row["headRefOid"].as_str() != Some(entry.head.as_str())
|| row["state"] != "OPEN"
Expand Down Expand Up @@ -286,6 +356,13 @@ fn rejection(row: &Value, entry: &Entry, queue_id: &str) -> Result<Option<Reject
removal_event: removal_event.to_owned(),
removed_at: removed_at.to_owned(),
notification_target: NotificationTarget::read(row),
publication: repository_id.map(|repository_id| PublicationBinding {
repository_id: repository_id.to_owned(),
queue_id: queue_id.to_owned(),
pr_head: entry.head.clone(),
absent: row.get("mergeQueueEntry") == Some(&Value::Null),
admission_upper_bound: admission_upper_bound(&row["admissions"]),
}),
merge_group_head: sha.to_owned(),
failed_required_check_runs: failed.keys().copied().collect(),
failed_required_workflows: failed
Expand All @@ -296,6 +373,21 @@ fn rejection(row: &Value, entry: &Entry, queue_id: &str) -> Result<Option<Reject
}))
}

fn admission_upper_bound(page: &Value) -> Option<u8> {
let nodes = page["nodes"].as_array().filter(|nodes| nodes.len() <= 3)?;
if page["pageInfo"]["hasPreviousPage"] != false || page["pageInfo"]["hasNextPage"] != false {
return None;
}
let mut ids = BTreeSet::new();
nodes
.iter()
.all(|row| {
row["__typename"] == "AddedToMergeQueueEvent"
&& node_id(&row["id"]).is_some_and(|id| ids.insert(id))
})
.then_some(nodes.len() as u8)
}

/// Validate a canonical UTC second before comparing GitHub event times.
pub(super) fn github_utc(value: &Value) -> Option<&str> {
value
Expand All @@ -308,6 +400,15 @@ mod tests {
use super::*;
use serde_json::json;

#[test]
fn admission_cap_counts_filtered_events_and_refuses_incomplete_pages() {
let mut page = json!({"totalCount":42,"pageInfo":{"hasPreviousPage":false,"hasNextPage":false},
"nodes":[{"__typename":"AddedToMergeQueueEvent","id":"E_admitted"}]});
assert_eq!(admission_upper_bound(&page), Some(1));
page["pageInfo"]["hasPreviousPage"] = json!(true);
assert_eq!(admission_upper_bound(&page), None);
}

#[test]
fn notification_target_requires_the_pr_and_a_supported_author_identity() {
let mut row = json!({"id":"pr-42"});
Expand Down
1 change: 1 addition & 0 deletions oxa/oxa-work/src/board/queue/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ mod tests {
removal_event: "removal".into(),
removed_at: "2026-01-01T00:09:00Z".into(),
notification_target: None,
publication: None,
merge_group_head: HEAD.into(),
failed_required_check_runs: vec![42],
failed_required_workflows: [(
Expand Down
84 changes: 73 additions & 11 deletions oxa/oxa-work/src/publish/landing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,21 @@ use serde_json::Value;
use std::{fs::File, path::Path};

const ADD_COMMENT: &str = "mutation($pr:ID!,$body:String!){addComment(input:{subjectId:$pr,body:$body}){
commentEdge{node{id repository{id} pullRequest{id} author{__typename
commentEdge{node{id repository{id} pullRequest{id headRefOid author{login ... on User{id} ... on Bot{id}}}
author{__typename
... on User{id} ... on Bot{id}} createdAt}}}}";
const ENQUEUE: &str = "mutation($pr:ID!,$head:GitObjectID!){enqueuePullRequest(input:{
pullRequestId:$pr,expectedHeadOid:$head}){mergeQueueEntry{id enqueuedAt
mergeQueue{id repository{id}} pullRequest{id headRefOid} headCommit{oid}}}}";
mergeQueue{id repository{id}} pullRequest{id number headRefOid} headCommit{oid}
enqueuer{__typename ... on User{id} ... on Bot{id}}}}}";

/// Identity supplied by the board Reader and matched to the owner journal.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct RejectedLanding {
pub repository_id: String,
pub queue_id: String,
pub pull_request_id: String,
pub pull_request_number: u64,
pub pr_head: String,
pub rejected_group: String,
pub removal_id: String,
Expand All @@ -41,6 +44,7 @@ impl RejectedLanding {
|| !is_object_id(&self.rejected_group)
|| self.rejected_group == self.pr_head
|| self.removed_at == 0
|| self.pull_request_number == 0
{
return Err("invalid rejected landing identity".into());
}
Expand Down Expand Up @@ -268,6 +272,9 @@ fn timestamp(value: &Value) -> Option<u64> {
fn delivery(intent: &NoticeIntent, node: &Value) -> Result<DeliveryReceipt> {
if node["repository"]["id"].as_str() != Some(&intent.rejection.repository_id)
|| node["pullRequest"]["id"].as_str() != Some(&intent.rejection.pull_request_id)
|| node["pullRequest"]["headRefOid"].as_str() != Some(&intent.rejection.pr_head)
|| node["pullRequest"]["author"]["id"].as_str() != Some(&intent.recipient_id)
|| node["pullRequest"]["author"]["login"].as_str() != Some(&intent.recipient_login)
|| !matches!(node["author"]["__typename"].as_str(), Some("User" | "Bot"))
|| node["author"]["id"].as_str() != Some(&intent.publisher_id)
{
Expand All @@ -290,6 +297,9 @@ fn admission(intent: &RetryIntent, entry: &Value) -> Result<Admission> {
|| entry["mergeQueue"]["id"].as_str() != Some(&rejection.queue_id)
|| entry["pullRequest"]["id"].as_str() != Some(&rejection.pull_request_id)
|| entry["pullRequest"]["headRefOid"].as_str() != Some(&rejection.pr_head)
|| entry["pullRequest"]["number"].as_u64() != Some(rejection.pull_request_number)
|| !matches!(entry["enqueuer"]["__typename"].as_str(), Some("User" | "Bot"))
|| entry["enqueuer"]["id"].as_str() != Some(&intent.delivery.intent.publisher_id)
{
return Err("admission acknowledgment does not match the landing reservation".into());
}
Expand Down Expand Up @@ -322,13 +332,13 @@ mod tests {
use super::*;
use serde_json::json;

#[test]
fn typed_landing_receipts_refuse_partial_and_mismatched_evidence() {
let intent = NoticeIntent {
fn test_intent() -> NoticeIntent {
NoticeIntent {
rejection: RejectedLanding {
repository_id: "R_repo".into(),
queue_id: "MQ_main".into(),
pull_request_id: "PR_pull".into(),
pull_request_number: 42,
pr_head: "a".repeat(40),
rejected_group: "b".repeat(40),
removal_id: "E_removed".into(),
Expand All @@ -337,21 +347,72 @@ mod tests {
recipient_id: "U_author".into(),
recipient_login: "synthetic-author".into(),
publisher_id: "U_publisher".into(),
}
}

#[test]
fn notice_uses_the_canonical_transport_on_a_mock_executable() {
use std::{fs, os::unix::fs::PermissionsExt};
let temp = crate::test_dir::PrivateDir::new("landing-transport");
let git = temp.path().join("git");
let gh = temp.path().join("gh");
fs::write(
&git,
"#!/bin/sh\nprintf '%s\\n' https://example.invalid/sample/repo\n",
)
.unwrap();
fs::write(&gh, r#"#!/bin/sh
test -z "${GH_TOKEN+x}" || exit 1
case "$*" in
'repo view https://example.invalid/sample/repo --json id,nameWithOwner,url')
printf '%s\n' '{"id":"R_repo","nameWithOwner":"sample/repo","url":"https://example.invalid/sample/repo"}' ;;
'api graphql --hostname example.invalid -f query=query{viewer{id}}')
printf '%s\n' '{"data":{"viewer":{"id":"U_publisher"}}}' ;;
'api graphql --hostname example.invalid -f query=mutation('*' pr=PR_pull -f body=@synthetic-author '*)
printf '%s\n' '{"data":{"addComment":{"commentEdge":{"node":{"id":"IC_comment",
"repository":{"id":"R_repo"},"pullRequest":{"id":"PR_pull","author":{"id":"U_author","login":"synthetic-author"},
"headRefOid":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
"author":{"__typename":"User","id":"U_publisher"},"createdAt":"1970-01-01T01:00:00Z"}}}}}'
;;
*) exit 1 ;;
esac
"#).unwrap();
for binary in [&git, &gh] {
fs::set_permissions(binary, fs::Permissions::from_mode(0o700)).unwrap();
}
let policy = RunPolicy {
git_binary: git,
host_path: Default::default(),
terminate_binary: None,
offline: false,
runner_owns_github: false,
storage: temp.path().to_owned(),
};
let log = crate::shadow::open_log(&temp.path().join("owner.jsonl")).unwrap();
let publisher = LandingPublisher::new(temp.path(), &policy, &gh, &log);
let receipt = publisher.notice(&test_intent(), &["synthetic::test"]).unwrap();
assert_eq!(receipt.comment_id, "IC_comment");
}

#[test]
fn typed_landing_receipts_refuse_partial_and_mismatched_evidence() {
let intent = test_intent();
let body = intent.body(&["suite::test`@unrelated"]).unwrap();
assert!(body.starts_with("@synthetic-author "));
assert!(body.ends_with("`suite::test’@unrelated`"));
assert!(intent
.body(&["bad
name"])
.is_err());
assert!(intent.body(&["bad\nname"]).is_err());
let mut node = json!({
"id":"IC_comment","repository":{"id":"R_repo"},"pullRequest":{"id":"PR_pull"},
"id":"IC_comment","repository":{"id":"R_repo"},
"pullRequest":{"id":"PR_pull","headRefOid":intent.rejection.pr_head,
"author":{"id":"U_author","login":"synthetic-author"}},
"author":{"__typename":"User","id":"U_publisher"},"createdAt":"1970-01-01T00:59:59Z"
});
assert!(delivery(&intent, &node).is_err());
node["createdAt"] = json!("1970-01-01T01:00:00Z");
let delivered = delivery(&intent, &node).unwrap();
node["pullRequest"]["author"]["id"] = json!("U_wrong_recipient");
assert!(delivery(&intent, &node).is_err());
node["pullRequest"]["author"]["id"] = json!("U_author");
node["author"]["id"] = json!("U_unrelated");
assert!(delivery(&intent, &node).is_err());
assert!(data(json!({"data":{"addComment": node},"errors":[{}]})).is_err());
Expand All @@ -369,7 +430,8 @@ name"])
let mut entry = json!({
"id":"MQE_entry","enqueuedAt":"1970-01-01T01:00:00Z",
"mergeQueue":{"id":"MQ_main","repository":{"id":"R_repo"}},
"pullRequest":{"id":"PR_pull","headRefOid":intent.rejection.pr_head},
"pullRequest":{"id":"PR_pull","number":42,"headRefOid":intent.rejection.pr_head},
"enqueuer":{"__typename":"User","id":"U_publisher"},
"headCommit":null
});
let Admission::Pending(pending) = admission(&retry, &entry).unwrap() else {
Expand Down
Loading