From 916f1580473bc9f083f8cea1afd2e7a085201cca Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 05:54:43 -0600 Subject: [PATCH 1/3] =?UTF-8?q?feat(fleet-queue):=20merge-intent=20stack?= =?UTF-8?q?=20storage=20=E2=80=94=20broker=20record/list=20over=20merge=5F?= =?UTF-8?q?intents=20(#8582=20increment=202)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../crates/fleet-queue/src/merge_intent.rs | 132 ++++++++++++- .../crates/fleet-queue/src/queue_broker.rs | 4 + .../crates/fleet-queue/src/turso_queue.rs | 186 +++++++++++++++++- 3 files changed, 319 insertions(+), 3 deletions(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs index 48f1b85781..d96bc669f9 100644 --- a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs +++ b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs @@ -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`: @@ -178,6 +179,69 @@ 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, + pub head_sha: Option, + pub issue_number: Option, + pub pr_number: Option, + pub owner_lane: String, + pub owner_worker: String, + pub owner_session: Option, +} + +/// 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}")); + } + } + 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`. +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)), + 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 @@ -430,6 +494,70 @@ 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 ddl_names_the_table_and_order_key() { assert!(MERGE_INTENT_DDL.contains("CREATE TABLE IF NOT EXISTS merge_intents")); diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 7cd465212f..e36f19e3f5 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -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}")}), } diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index bfaf60d21a..65b5fa81cc 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -864,7 +864,7 @@ impl Clone for Arg { } } -const SCHEMA: [&str; 16] = [ +const SCHEMA: [&str; 17] = [ "CREATE TABLE IF NOT EXISTS tasks (\ id INTEGER PRIMARY KEY AUTOINCREMENT, \ queue TEXT NOT NULL, title TEXT, body TEXT, \ @@ -934,6 +934,9 @@ const SCHEMA: [&str; 16] = [ id INTEGER PRIMARY KEY CHECK (id = 1), \ consecutive_rate_limits INTEGER NOT NULL DEFAULT 0, \ open_until TEXT, last_error_class TEXT, updated_at TEXT NOT NULL)", + // #8582 increment 2: the merge-intent table, DDL of record in + // the pure core module. + crate::merge_intent::MERGE_INTENT_DDL, ]; // --------------------------------------------------------------------------- @@ -6427,6 +6430,155 @@ fn verb_health(t: &TursoBackend, req: &Value) -> Value { } } +// --------------------------------------------------------------------------- +// Merge-intent stack storage (#8582 increment 2) — broker endpoints +// over the merge_intents table (DDL of record: +// crate::merge_intent::MERGE_INTENT_DDL, applied via SCHEMA above). +// Record/list only: the replay executor is a later increment. The +// append rules themselves (position, base tip) are the pure core's +// (plan_append), so storage cannot drift from replay semantics, and +// a stack's full state — branches, order, owners — reads back from +// this database alone while GitHub is down. +// --------------------------------------------------------------------------- + +const MERGE_INTENT_COLS: &str = "id, stack_id, position, repo, branch, base_branch, \ + head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ + state, conflict_detail, created_at, updated_at"; + +fn merge_intent_core(row: &Value) -> Option { + Some(crate::merge_intent::MergeIntent { + stack_id: row.get("stack_id")?.as_str()?.to_string(), + position: row.get("position")?.as_i64()?, + repo: row.get("repo")?.as_str()?.to_string(), + branch: row.get("branch")?.as_str()?.to_string(), + base_branch: row.get("base_branch")?.as_str()?.to_string(), + head_sha: row + .get("head_sha") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), + issue_number: row.get("issue_number").and_then(|v| v.as_i64()), + pr_number: row.get("pr_number").and_then(|v| v.as_i64()), + owner_lane: row.get("owner_lane")?.as_str()?.to_string(), + owner_worker: row.get("owner_worker")?.as_str()?.to_string(), + owner_session: row + .get("owner_session") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), + state: crate::merge_intent::IntentState::parse(row.get("state")?.as_str()?)?, + }) +} + +fn stack_rows(t: &TursoBackend, stack_id: &str) -> Result, TErr> { + t.query_objs( + &format!( + "SELECT {MERGE_INTENT_COLS} FROM merge_intents \ + WHERE stack_id = ? ORDER BY position ASC" + ), + &[Arg::Text(stack_id.to_string())], + &[], + ) +} + +/// The stack state the list endpoint answers: every recorded intent +/// in merge order, plus the core's derived view (the replay walk, +/// and where the next append lands) — all from the database alone. +fn stack_state(stack_id: &str, rows: &[Value]) -> Value { + let core: Vec = + rows.iter().filter_map(merge_intent_core).collect(); + let walk: Vec = crate::merge_intent::replay_prefix(&core, stack_id) + .iter() + .map(|i| { + json!({ + "position": i.position, + "branch": i.branch, + "base_branch": i.base_branch, + }) + }) + .collect(); + json!({ + "stack_id": stack_id, + "intents": rows, + "replay_prefix": walk, + "next_position": crate::merge_intent::next_position(&core, stack_id), + "next_base_branch": crate::merge_intent::next_base_branch(&core, stack_id), + }) +} + +fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { + let append = crate::merge_intent::AppendRequest { + stack_id: req_str(req, "stack_id").unwrap_or("").to_string(), + repo: req_str(req, "repo").unwrap_or("").to_string(), + branch: req_str(req, "branch").unwrap_or("").to_string(), + base_branch: req_str(req, "base_branch").map(|s| s.to_string()), + head_sha: req_str(req, "head_sha").map(|s| s.to_string()), + issue_number: req_i64(req, "issue_number"), + pr_number: req_i64(req, "pr_number"), + owner_lane: req_str(req, "owner_lane").unwrap_or("").to_string(), + owner_worker: req_str(req, "owner_worker").unwrap_or("").to_string(), + owner_session: req_str(req, "owner_session").map(|s| s.to_string()), + }; + if let Err(e) = crate::merge_intent::validate_append(&append) { + return fail(2, e); + } + let work = (|| -> Result { + let existing_rows = stack_rows(t, &append.stack_id)?; + let existing: Vec = + existing_rows.iter().filter_map(merge_intent_core).collect(); + let planned = crate::merge_intent::plan_append(&existing, &append); + let now = now_iso(); + let res = t.exec( + "INSERT INTO merge_intents (stack_id, position, repo, branch, base_branch, \ + head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ + state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + &[ + Arg::Text(planned.stack_id.clone()), + Arg::Int(planned.position), + Arg::Text(planned.repo.clone()), + Arg::Text(planned.branch.clone()), + Arg::Text(planned.base_branch.clone()), + arg_str(planned.head_sha.as_deref()), + planned.issue_number.map(Arg::Int).unwrap_or(Arg::Null), + planned.pr_number.map(Arg::Int).unwrap_or(Arg::Null), + Arg::Text(planned.owner_lane.clone()), + Arg::Text(planned.owner_worker.clone()), + arg_str(planned.owner_session.as_deref()), + Arg::Text(planned.state.as_str().to_string()), + Arg::Text(now.clone()), + Arg::Text(now), + ], + )?; + let rows = stack_rows(t, &append.stack_id)?; + let inserted = rows + .iter() + .find(|r| r.get("id").and_then(|v| v.as_i64()) == res.last_insert_rowid) + .cloned() + .unwrap_or(Value::Null); + Ok(json!({ + "intent": inserted, + "stack": stack_state(&append.stack_id, &rows), + })) + })(); + match work { + Ok(v) => ok(json!({"row": v})), + Err(e) => terr(e), + } +} + +fn verb_stack_list(t: &TursoBackend, req: &Value) -> Value { + let Some(stack_id) = req_str(req, "stack_id") else { + return fail(2, "stack_id is required".to_string()); + }; + let stack_id = stack_id.to_string(); + let work = (|| -> Result { + let rows = stack_rows(t, &stack_id)?; + Ok(stack_state(&stack_id, &rows)) + })(); + match work { + Ok(v) => ok(json!({"row": v})), + Err(e) => terr(e), + } +} + fn verb_signal_count(t: &TursoBackend, req: &Value) -> Value { let queue = req_str(req, "queue").unwrap_or("").to_string(); let work = (|| -> Result { @@ -7016,6 +7168,8 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/list" => verb_list(t, req), "/health" => verb_health(t, req), "/signal-count" => verb_signal_count(t, req), + "/stack-record" => verb_stack_record(t, req), + "/stack-list" => verb_stack_list(t, req), "/events-append" => verb_events_append(t, req), "/events-seen" => verb_events_seen(t, req), "/events-count" => verb_events_count(t, req), @@ -7036,6 +7190,36 @@ mod tests { use super::*; use proptest::prelude::*; + #[test] + fn stack_storage_wiring_8582() { + // Source oracle for increment 2 of #8582: the schema applies + // the core's DDL of record, dispatch routes both stack + // verbs, and the record verb decides validation + append + // planning in the pure core (never in SQL). + let src = include_str!("turso_queue.rs"); + assert!( + src.contains("crate::merge_intent::MERGE_INTENT_DDL"), + "schema applies the merge_intents DDL of record" + ); + let dispatch_seg = seg8217(src, "pub fn dispatch(", "\n#[cfg(test)]"); + assert!( + dispatch_seg.contains("\"/stack-record\" => verb_stack_record(t, req)"), + "dispatch routes /stack-record" + ); + assert!( + dispatch_seg.contains("\"/stack-list\" => verb_stack_list(t, req)"), + "dispatch routes /stack-list" + ); + let record = seg8217(src, "fn verb_stack_record(", "\nfn verb_stack_list("); + assert!( + record.contains("validate_append("), + "record validates via the core" + ); + assert!(record.contains("plan_append("), "record plans via the core"); + let list = seg8217(src, "fn verb_stack_list(", "\nfn verb_signal_count("); + assert!(list.contains("stack_state("), "list answers the derived stack state"); + } + #[test] fn canonical_lanes_are_exactly_the_post_rename_universe_8097() { // #8097 oracle: after the 2026-11-11 lane rename + trims, From 876eff7ef7280975f28c7222d59338eafda6de78 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 07:09:20 -0600 Subject: [PATCH 2/3] fix(fleet-queue): retry stack append on position conflict (#8582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex P2 on PR #8660: two lanes recording into the same stack concurrently could read the same rows, plan the same next position, and the loser hit UNIQUE(stack_id, position), leaving its branch unrecorded. verb_stack_record now retries the whole read/plan/insert cycle up to 5 attempts when the INSERT fails with a stack_id UNIQUE conflict, so position and base branch are recalculated from the winners row. Other errors — including the UNIQUE(repo, branch) duplicate-branch refusal — return immediately. fleet-queue tests: 44/44 default, 260/260 with queue-broker. --- .../crates/fleet-queue/src/turso_queue.rs | 94 ++++++++++++------- 1 file changed, 58 insertions(+), 36 deletions(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 65b5fa81cc..1ed9fc879d 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -6521,42 +6521,64 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { return fail(2, e); } let work = (|| -> Result { - let existing_rows = stack_rows(t, &append.stack_id)?; - let existing: Vec = - existing_rows.iter().filter_map(merge_intent_core).collect(); - let planned = crate::merge_intent::plan_append(&existing, &append); - let now = now_iso(); - let res = t.exec( - "INSERT INTO merge_intents (stack_id, position, repo, branch, base_branch, \ - head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ - state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - &[ - Arg::Text(planned.stack_id.clone()), - Arg::Int(planned.position), - Arg::Text(planned.repo.clone()), - Arg::Text(planned.branch.clone()), - Arg::Text(planned.base_branch.clone()), - arg_str(planned.head_sha.as_deref()), - planned.issue_number.map(Arg::Int).unwrap_or(Arg::Null), - planned.pr_number.map(Arg::Int).unwrap_or(Arg::Null), - Arg::Text(planned.owner_lane.clone()), - Arg::Text(planned.owner_worker.clone()), - arg_str(planned.owner_session.as_deref()), - Arg::Text(planned.state.as_str().to_string()), - Arg::Text(now.clone()), - Arg::Text(now), - ], - )?; - let rows = stack_rows(t, &append.stack_id)?; - let inserted = rows - .iter() - .find(|r| r.get("id").and_then(|v| v.as_i64()) == res.last_insert_rowid) - .cloned() - .unwrap_or(Value::Null); - Ok(json!({ - "intent": inserted, - "stack": stack_state(&append.stack_id, &rows), - })) + // Concurrent lanes recording into the same stack can read the + // same rows and plan the same next position; the loser's INSERT + // then hits UNIQUE(stack_id, position). Retry the whole + // read/plan/insert cycle on that conflict so position AND base + // branch are recalculated from the winner's row (Codex P2 on + // PR #8660). Other errors — including the UNIQUE(repo, branch) + // duplicate-branch refusal — return immediately. + let mut attempt = 0; + loop { + attempt += 1; + let existing_rows = stack_rows(t, &append.stack_id)?; + let existing: Vec = + existing_rows.iter().filter_map(merge_intent_core).collect(); + let planned = crate::merge_intent::plan_append(&existing, &append); + let now = now_iso(); + let res = t.exec( + "INSERT INTO merge_intents (stack_id, position, repo, branch, base_branch, \ + head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ + state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + &[ + Arg::Text(planned.stack_id.clone()), + Arg::Int(planned.position), + Arg::Text(planned.repo.clone()), + Arg::Text(planned.branch.clone()), + Arg::Text(planned.base_branch.clone()), + arg_str(planned.head_sha.as_deref()), + planned.issue_number.map(Arg::Int).unwrap_or(Arg::Null), + planned.pr_number.map(Arg::Int).unwrap_or(Arg::Null), + Arg::Text(planned.owner_lane.clone()), + Arg::Text(planned.owner_worker.clone()), + arg_str(planned.owner_session.as_deref()), + Arg::Text(planned.state.as_str().to_string()), + Arg::Text(now.clone()), + Arg::Text(now), + ], + ); + let res = match res { + Ok(res) => res, + Err(e) + if attempt < 5 + && e.contains("UNIQUE constraint failed") + && e.contains("stack_id") => + { + continue; + } + Err(e) => return Err(e), + }; + let rows = stack_rows(t, &append.stack_id)?; + let inserted = rows + .iter() + .find(|r| r.get("id").and_then(|v| v.as_i64()) == res.last_insert_rowid) + .cloned() + .unwrap_or(Value::Null); + return Ok(json!({ + "intent": inserted, + "stack": stack_state(&append.stack_id, &rows), + })); + } })(); match work { Ok(v) => ok(json!({"row": v})), From ca416f5faca896847c25627c3f075a9dbaf5ef84 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Wed, 11 Nov 2026 07:41:21 -0600 Subject: [PATCH 3/3] fix(fleet-queue): reject blank explicit base and cross-repo stack appends (#8582) CodeRabbit findings on PR #8660: validate_append now rejects a blank explicit base_branch, and /stack-record refuses an append whose repo differs from the rows already recorded under its stack_id (new pure-core validate_append_against_stack, checked before planning and again under the retry loop). Two new oracle tests; fleet-queue 46/46 pass. --- .../crates/fleet-queue/src/merge_intent.rs | 58 ++++++++++++++++++- .../crates/fleet-queue/src/turso_queue.rs | 15 +++++ 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs index d96bc669f9..ca3fda8318 100644 --- a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs +++ b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs @@ -215,13 +215,45 @@ pub fn validate_append(req: &AppendRequest) -> Result<(), String> { 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`. +/// 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(), @@ -558,6 +590,30 @@ mod tests { } } + #[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")); diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 1ed9fc879d..fcc383ce9a 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -6520,6 +6520,18 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { if let Err(e) = crate::merge_intent::validate_append(&append) { return fail(2, e); } + // One stack, one repository (#8582): refuse a cross-repo append + // before planning — plan_append would otherwise base the new + // branch on a tip from the other repository (CodeRabbit finding, + // PR #8660). A read failure here is not a verdict: the work + // closure below re-reads under the retry loop and surfaces it. + if let Ok(pre_rows) = stack_rows(t, &append.stack_id) { + let pre_existing: Vec = + pre_rows.iter().filter_map(merge_intent_core).collect(); + if let Err(e) = crate::merge_intent::validate_append_against_stack(&pre_existing, &append) { + return fail(2, e); + } + } let work = (|| -> Result { // Concurrent lanes recording into the same stack can read the // same rows and plan the same next position; the loser's INSERT @@ -6534,6 +6546,9 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { let existing_rows = stack_rows(t, &append.stack_id)?; let existing: Vec = existing_rows.iter().filter_map(merge_intent_core).collect(); + // Safety net for a cross-repo row landing between the + // pre-check below and this read: never plan on its tip. + crate::merge_intent::validate_append_against_stack(&existing, &append)?; let planned = crate::merge_intent::plan_append(&existing, &append); let now = now_iso(); let res = t.exec(