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
188 changes: 186 additions & 2 deletions pkgs/fleet/crates/fleet-queue/src/merge_intent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@
//!
//! This module is the pure core: the table DDL of record, the row
//! shape, the ordering and state-transition rules, and conflict
//! routing. Broker endpoints, client verbs, and the replay executor
//! build on it in follow-on increments; nothing here does I/O.
//! routing. The broker's storage endpoints (increment 2, in
//! `turso_queue`) build on it; client verbs and the replay executor
//! follow in later increments. Nothing here does I/O.

/// DDL of record for the merge-intent table (fleet-queue database).
/// `position` is the recorded merge order inside one `stack_id`:
Expand Down Expand Up @@ -178,6 +179,101 @@ pub fn next_base_branch(existing: &[MergeIntent], stack_id: &str) -> String {
.map_or_else(|| "main".to_string(), |i| i.branch.clone())
}

/// A request to append one finished branch to a stack, as recorded
/// by the authoring lane during an outage (#8582 increment 2). The
/// broker's record endpoint builds this from the request body; the
/// append rules (position, base) are decided here, in the pure core,
/// so the storage layer cannot drift from the replay semantics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppendRequest {
pub stack_id: String,
pub repo: String,
pub branch: String,
pub base_branch: Option<String>,
pub head_sha: Option<String>,
pub issue_number: Option<i64>,
pub pr_number: Option<i64>,
pub owner_lane: String,
pub owner_worker: String,
pub owner_session: Option<String>,
}

/// The fields an append must carry to be recorded: a stack, a repo,
/// a branch, and the authoring owner (lane + worker) a later
/// conflict will be routed to. An append without an owner is
/// rejected — recording it would strand its replay conflict with
/// nobody to route to.
pub fn validate_append(req: &AppendRequest) -> Result<(), String> {
for (field, value) in [
("stack_id", &req.stack_id),
("repo", &req.repo),
("branch", &req.branch),
("owner_lane", &req.owner_lane),
("owner_worker", &req.owner_worker),
] {
if value.trim().is_empty() {
return Err(format!("merge-intent record requires a non-empty {field}"));
}
}
if let Some(base) = &req.base_branch {
if base.trim().is_empty() {
return Err(
"merge-intent record requires a non-empty base_branch when one is given"
.to_string(),
);
}
}
Ok(())
}

/// A stack lives in one repository: an append naming a different
/// repo than the rows already recorded under its `stack_id` is
/// rejected — otherwise [`plan_append`] would base the new branch
/// on a tip from another repository (CodeRabbit finding, PR #8660).
pub fn validate_append_against_stack(
existing: &[MergeIntent],
req: &AppendRequest,
) -> Result<(), String> {
if let Some(other) = existing
.iter()
.find(|i| i.stack_id == req.stack_id && i.repo != req.repo)
{
return Err(format!(
"merge-intent stack {} already records repo {}; refusing append for repo {}",
req.stack_id, other.repo, req.repo
));
}
Ok(())
}

/// Plan the row an append inserts: position from [`next_position`],
/// base from the request's explicit base or [`next_base_branch`]
/// (the current tip, so each new branch stacks on the previous
/// one), state `intended`. The inferred base is the stack
/// construction contract — a branch recorded without an explicit
/// base asserts it was built on the stack tip; a caller whose
/// branch was built on a different base passes that real base
/// explicitly (see [`AppendRequest::base_branch`]).
pub fn plan_append(existing: &[MergeIntent], req: &AppendRequest) -> MergeIntent {
MergeIntent {
stack_id: req.stack_id.clone(),
position: next_position(existing, &req.stack_id),
repo: req.repo.clone(),
branch: req.branch.clone(),
base_branch: req
.base_branch
.clone()
.unwrap_or_else(|| next_base_branch(existing, &req.stack_id)),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
head_sha: req.head_sha.clone(),
issue_number: req.issue_number,
pr_number: req.pr_number,
owner_lane: req.owner_lane.clone(),
owner_worker: req.owner_worker.clone(),
owner_session: req.owner_session.clone(),
state: IntentState::Intended,
}
}

/// The replay walk for one stack: the `intended` intents in recorded
/// order, bottom first. Finished entries — `landed` (already merged
/// by an earlier replay pass) and `abandoned` (withdrawn) — are
Expand Down Expand Up @@ -430,6 +526,94 @@ mod tests {
}
}

fn append_req(stack: &str, branch: &str) -> AppendRequest {
AppendRequest {
stack_id: stack.to_string(),
repo: "developing-today/code".to_string(),
branch: branch.to_string(),
base_branch: None,
head_sha: None,
issue_number: Some(8582),
pr_number: None,
owner_lane: "code-c".to_string(),
owner_worker: "repo-worker-code".to_string(),
owner_session: None,
}
}

#[test]
fn plan_append_stacks_on_the_tip_in_finish_order() {
// Oracle: the #8582 stacking rule stated in the issue — each
// new branch is based on the previous branch's tip, and the
// recorded position is the order work finished in.
let first = plan_append(&[], &append_req("s1", "queue/a"));
assert_eq!(first.position, 0);
assert_eq!(first.base_branch, "main");
assert_eq!(first.state, IntentState::Intended);
let second = plan_append(&[first], &append_req("s1", "queue/b"));
assert_eq!(second.position, 1);
assert_eq!(second.base_branch, "queue/a");
// A different stack is independent: it starts at main again.
let other = plan_append(&[second.clone()], &append_req("s2", "queue/c"));
assert_eq!(other.position, 0);
assert_eq!(other.base_branch, "main");
// An abandoned tip never becomes the next base.
let mut dead = second;
dead.state = IntentState::Abandoned;
let third = plan_append(&[dead], &append_req("s1", "queue/d"));
assert_eq!(third.base_branch, "main");
}

#[test]
fn plan_append_honors_an_explicit_base() {
let mut req = append_req("s1", "queue/b");
req.base_branch = Some("release/x".to_string());
let planned = plan_append(&[intent("s1", 0, "queue/a", IntentState::Intended)], &req);
assert_eq!(planned.base_branch, "release/x");
assert_eq!(planned.position, 1);
}

#[test]
fn validate_append_requires_stack_repo_branch_and_owner() {
assert!(validate_append(&append_req("s1", "queue/a")).is_ok());
for blank in ["stack_id", "repo", "branch", "owner_lane", "owner_worker"] {
let mut req = append_req("s1", "queue/a");
match blank {
"stack_id" => req.stack_id = " ".to_string(),
"repo" => req.repo = String::new(),
"branch" => req.branch = String::new(),
"owner_lane" => req.owner_lane = String::new(),
_ => req.owner_worker = String::new(),
}
let err = validate_append(&req).expect_err("blank field must be rejected");
assert!(err.contains(blank), "{err}");
}
}

#[test]
fn validate_append_rejects_a_blank_explicit_base() {
// Oracle: a recorded base must be a branch replay can rebase
// onto; an explicit blank base is not one (CodeRabbit, PR #8660).
let mut req = append_req("s1", "queue/a");
req.base_branch = Some(" ".to_string());
let err = validate_append(&req).expect_err("blank explicit base must be rejected");
assert!(err.contains("base_branch"), "{err}");
}

#[test]
fn validate_append_against_stack_rejects_a_repo_mismatch() {
// Oracle: one stack, one repository — a tip from another
// repo can never be this stack's base (CodeRabbit, PR #8660).
let existing = vec![intent("s1", 0, "queue/a", IntentState::Intended)];
assert!(validate_append_against_stack(&existing, &append_req("s1", "queue/b")).is_ok());
assert!(validate_append_against_stack(&existing, &append_req("s2", "queue/b")).is_ok());
let mut foreign = append_req("s1", "queue/b");
foreign.repo = "developing-today-forks/opencode".to_string();
let err = validate_append_against_stack(&existing, &foreign)
.expect_err("cross-repo append must be rejected");
assert!(err.contains("already records repo"), "{err}");
}

#[test]
fn ddl_names_the_table_and_order_key() {
assert!(MERGE_INTENT_DDL.contains("CREATE TABLE IF NOT EXISTS merge_intents"));
Expand Down
4 changes: 4 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/queue_broker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,10 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value {
Err(e) => fail(e.exit, e.msg),
}
}
"/stack-record" | "/stack-list" => fail(
2,
"merge-intent stack verbs require the turso queue backend (#8582)".to_string(),
),
"/healthz" => ok(json!({"service": "queue-broker"})),
_ => json!({"ok": false, "exit": 2, "error": format!("unknown command {path}")}),
}
Expand Down
Loading
Loading