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
258 changes: 255 additions & 3 deletions pkgs/fleet/crates/fleet-queue/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,10 @@ fn parse_args(rest: &[String], flags: &[&str], bools: &[&str]) -> Args {
/// (e.g. `--queue a --queue b` recorded queue=b), and a boolean given
/// an inline value (`--dry-run=false`) used to be read as `true` —
/// a real enqueue silently became a dry run that enqueued nothing
/// and exited 0.
/// and exited 0. A value flag followed by another flag token is the
/// same class (#8582, Codex P1 on PR #8790): the flag token is not a
/// value — `--head-sha --dry-run` used to persist "--dry-run" as the
/// SHA on a mutating stack record instead of erroring.
fn parse_args_inner(rest: &[String], flags: &[&str], bools: &[&str]) -> Result<Args, String> {
let mut pos = Vec::new();
let mut opts = Map::new();
Expand All @@ -870,7 +873,7 @@ fn parse_args_inner(rest: &[String], flags: &[&str], bools: &[&str]) -> Result<A
if let Some(v) = inline {
opts.insert(name, Value::String(v));
i += 1;
} else if i + 1 < rest.len() {
} else if i + 1 < rest.len() && !rest[i + 1].starts_with("--") {
opts.insert(name, Value::String(rest[i + 1].clone()));
i += 2;
} else {
Expand Down Expand Up @@ -3460,6 +3463,142 @@ fn cmd_outbox_drain(rest: &[String]) -> i32 {
0
}

/// Merge-intent stack verbs (#8582 increment 3): the client surface
/// for the broker's /stack-record and /stack-list routes (increment
/// 2). Recording a finished branch names its authoring lane/worker
/// pair; the broker validates that pair against the lane registry
/// (the validation deferred from the CodeRabbit round on PR #8660,
/// where the pair originates — here, at the client verbs).
/// Stack list answers the full stack state from the database alone.
pub(crate) fn stack_record_body(
stack_id: &str,
repo: &str,
branch: &str,
base_branch: Option<&str>,
head_sha: Option<&str>,
issue_number: Option<i64>,
pr_number: Option<i64>,
owner_lane: &str,
owner_worker: &str,
owner_session: Option<&str>,
) -> Result<Value, String> {
// Fail fast with the pure core's own append rules, so a bad
// record is a usage error here and the identical verdict at
// the broker (validate_append is the one rule set, #8582).
let append = crate::merge_intent::AppendRequest {
stack_id: stack_id.to_string(),
repo: repo.to_string(),
branch: branch.to_string(),
base_branch: base_branch.map(|s| s.to_string()),
head_sha: head_sha.map(|s| s.to_string()),
issue_number,
pr_number,
owner_lane: owner_lane.to_string(),
owner_worker: owner_worker.to_string(),
owner_session: owner_session.map(|s| s.to_string()),
};
crate::merge_intent::validate_append(&append)?;
Ok(json!({
"stack_id": stack_id,
"repo": repo,
"branch": branch,
"base_branch": base_branch,
"head_sha": head_sha,
"issue_number": issue_number,
"pr_number": pr_number,
"owner_lane": owner_lane,
"owner_worker": owner_worker,
"owner_session": owner_session,
}))
}

fn cmd_stack_record(rest: &[String]) -> i32 {
let args = parse_args(
rest,
&[
"stack",
"repo",
"branch",
"base-branch",
"head-sha",
"issue",
"pr",
"lane",
"worker",
"session-id",
],
&[],
);
reject_extra_pos("stack record", &args, 0);
let stack_id = args
.get("stack")
.unwrap_or_else(|| die(2, "stack record: --stack is required"));
let repo = args
.get("repo")
.unwrap_or_else(|| die(2, "stack record: --repo is required"));
let branch = args
.get("branch")
.unwrap_or_else(|| die(2, "stack record: --branch is required"));
// The owner pair originates here (#8582): the authoring lane is
// required, and the worker defaults to this caller's worker —
// the broker refuses a pair the lane registry does not hold.
let owner_lane = args
.get("lane")
.unwrap_or_else(|| die(2, "stack record: --lane is required (the authoring lane)"));
let body = match stack_record_body(
&stack_id,
&repo,
&branch,
args.get("base-branch").as_deref(),
args.get("head-sha").as_deref(),
Comment thread
dezren39 marked this conversation as resolved.
Resolved
args.get_i64("issue"),
args.get_i64("pr"),
&owner_lane,
&opt_worker(&args),
args.get("session-id").as_deref(),
) {
Ok(b) => b,
Err(e) => die(2, &e),
};
let resp = unwrap_ok(call("/stack-record", &body));
print_json(&require_row(&resp, "stack_record"));
0
}

fn cmd_stack_list(rest: &[String]) -> i32 {
let args = parse_args(rest, &["stack", "worker"], &[]);
reject_extra_pos("stack list", &args, 1);
let positional = args.pos.first().cloned();
let stack_id = match (positional, args.get("stack")) {
(Some(p), Some(f)) if p != f => {
die(2, "stack list: positional stack id and --stack disagree")
}
(Some(p), _) => p,
(None, Some(f)) => f,
(None, None) => die(2, "stack list: a stack id is required"),
};
let resp = unwrap_ok(call("/stack-list", &json!({"stack_id": stack_id})));
print_json(&require_row(&resp, "stack_list"));
0
}

fn cmd_stack(rest: &[String]) -> i32 {
if rest.is_empty() {
eprint("usage: repo-queue stack <record|list> ...");
return 2;
}
let sub = rest[0].as_str();
let tail = &rest[1..];
match sub {
"record" => cmd_stack_record(tail),
"list" => cmd_stack_list(tail),
_ => {
eprint(&format!("repo-queue: unknown stack command {sub:?}"));
2
}
}
}

fn cmd_outbox(rest: &[String]) -> i32 {
if rest.is_empty() {
eprint("usage: repo-queue outbox <enqueue|list|metrics|claim|resolve|drain> ...");
Expand All @@ -3483,7 +3622,7 @@ fn cmd_outbox(rest: &[String]) -> i32 {
pub fn run(args: &[String]) -> i32 {
if args.is_empty() {
eprint(
"usage: repo-queue <validate|list|enqueue|claim|release|lane|bind|heartbeat|checkpoint|park|wake|block|unblock|dep-recheck|cancel|fail|complete|revive|health|signal|fallback|outbox|dispatch|session|surfaces> ...",
"usage: repo-queue <validate|list|enqueue|claim|release|lane|bind|heartbeat|checkpoint|park|wake|block|unblock|dep-recheck|cancel|fail|complete|revive|health|signal|fallback|outbox|dispatch|session|surfaces|stack> ...",
);
return 2;
}
Expand Down Expand Up @@ -3518,6 +3657,7 @@ pub fn run(args: &[String]) -> i32 {
"session" => crate::placement::cmd_session(rest),
"surfaces" => crate::placement::cmd_surfaces(rest),
"outbox" => cmd_outbox(rest),
"stack" => cmd_stack(rest),
_ => {
eprint(&format!("repo-queue: unknown command {sub:?}"));
2
Expand Down Expand Up @@ -3584,6 +3724,77 @@ mod tests {
assert!(batch_count_flag(Some(crate::turso_queue::BATCH_CLAIM_MAX + 1)).is_err());
}

#[test]
fn stack_record_body_carries_the_append_shape_8582() {
// #8582 increment 3 oracle: the client record body is
// exactly the broker's append shape (stack, repo, branch,
// owner lane/worker pair, optional base/head/issue/pr/
// session), and the pure core's append rules are the
// client's fail-fast rules too — an ownerless or
// branchless record never reaches the broker.
let body = stack_record_body(
"outage-2026-11-11",
"developing-today/code",
"queue/1-2-fix",
None,
Some("abc123"),
Some(8582),
None,
"any-a",
"repo-worker-code",
Some("ses_1"),
)
.expect("a complete append is valid");
assert_eq!(body["stack_id"], json!("outage-2026-11-11"));
assert_eq!(body["repo"], json!("developing-today/code"));
assert_eq!(body["branch"], json!("queue/1-2-fix"));
assert_eq!(body["base_branch"], Value::Null);
assert_eq!(body["head_sha"], json!("abc123"));
assert_eq!(body["issue_number"], json!(8582));
assert_eq!(body["owner_lane"], json!("any-a"));
assert_eq!(body["owner_worker"], json!("repo-worker-code"));
assert_eq!(body["owner_session"], json!("ses_1"));
assert!(stack_record_body(
"s",
"developing-today/code",
"queue/1-2-fix",
None,
None,
None,
None,
"",
"repo-worker-code",
None,
)
.is_err());
assert!(stack_record_body(
"s",
"developing-today/code",
"",
None,
None,
None,
None,
"any-a",
"repo-worker-code",
None,
)
.is_err());
assert!(stack_record_body(
"s",
"developing-today/code",
"queue/1-2-fix",
Some(" "),
None,
None,
None,
"any-a",
"repo-worker-code",
None,
)
.is_err());
}

#[test]
fn fallback_switch_json_shape() {
let v = fallback_switch_json("/claim", 4, "store down");
Expand Down Expand Up @@ -3819,6 +4030,47 @@ mod tests {
assert!(parse_args_inner(&pos(&["--queue=a", "--queue", "b"]), &["queue"], &[]).is_err());
}

#[test]
fn flag_token_as_value_is_a_usage_error() {
// #8582 (Codex P1 on PR #8790): a value flag followed by a flag
// token used to consume that token as its value, so
// `stack record --head-sha --dry-run` persisted "--dry-run" as
// the head SHA on a mutating broker call instead of erroring.
// Oracle: the operator argument contract (AGENTS.md #3352) - a
// present-but-valueless option is a usage error naming the flag.
let err = parse_args_inner(
&pos(&["--head-sha", "--dry-run"]),
&["head-sha"],
&["dry-run"],
)
.err()
.expect("flag token must not be consumed as a value");
assert!(err.contains("--head-sha"), "error names the flag: {err}");
assert!(
err.contains("expected one argument"),
"error names the defect: {err}"
);
// Any flag-shaped token is refused, known or not, and the
// refusal fires even when a well-formed flag follows it.
assert!(
parse_args_inner(
&pos(&["--queue", "--bogus", "--limit", "5"]),
&["queue", "limit"],
&[]
)
.is_err()
);
// Ordinary values still parse, including single-dash values.
let args = parse_args_inner(&pos(&["--queue", "alpha"]), &["queue"], &[])
.ok()
.expect("ordinary value parses");
assert_eq!(args.get("queue").as_deref(), Some("alpha"));
let args = parse_args_inner(&pos(&["--limit", "-1"]), &["limit"], &[])
.ok()
.expect("single-dash value parses");
assert_eq!(args.get("limit").as_deref(), Some("-1"));
}

#[test]
fn duplicate_bool_flag_is_a_usage_error() {
let err = parse_args_inner(&pos(&["--dry-run", "--dry-run"]), &[], &["dry-run"])
Expand Down
53 changes: 53 additions & 0 deletions pkgs/fleet/crates/fleet-queue/src/turso_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6520,6 +6520,48 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value {
if let Err(e) = crate::merge_intent::validate_append(&append) {
return fail(2, e);
}
// Owner lane/worker pair validation against the lane registry
// (#8582 increment 3; deferred from the CodeRabbit round on
// PR #8660, where the pair originates at the client verbs):
// a recorded intent's conflict is routed to its owner pair, so
// the pair must be one the registry actually holds — an
// unknown lane, a lane owned by a different worker, or a
// disabled lane would strand that routing. Mirrors the claim
// preamble's registry check (minus the queue binding: stack
// recording is not a claim).
{
let lanes = match t.query_objs(
"SELECT lane_id, worker_id, enabled FROM lanes WHERE lane_id = ?",
&[Arg::Text(append.owner_lane.clone())],
&[],
) {
Ok(rows) => rows,
Err(e) => return terr(e),
};
let Some(l) = lanes.into_iter().next() else {
return fail(
2,
format!("stack_record: unknown owner lane_id {}", append.owner_lane),
);
};
if l.get("worker_id").and_then(|v| v.as_str()) != Some(append.owner_worker.as_str()) {
return fail(
2,
format!(
"stack_record: lane {} belongs to worker {}, not {}",
append.owner_lane,
l.get("worker_id").and_then(|v| v.as_str()).unwrap_or(""),
append.owner_worker
),
);
}
if l.get("enabled").and_then(|v| v.as_i64()) == Some(0) {
return fail(
2,
format!("stack_record: lane {} is disabled", append.owner_lane),
);
}
}
// 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,
Expand Down Expand Up @@ -7253,6 +7295,17 @@ mod tests {
"record validates via the core"
);
assert!(record.contains("plan_append("), "record plans via the core");
// Increment 3: the record verb validates the owner
// lane/worker pair against the lanes registry, so a
// conflict route recorded here names a real owner.
assert!(
record.contains("FROM lanes WHERE lane_id = ?"),
"record validates the owner pair against the lane registry"
);
assert!(
record.contains("unknown owner lane_id"),
"record refuses an unregistered owner lane"
);
let list = seg8217(src, "fn verb_stack_list(", "\nfn verb_signal_count(");
assert!(list.contains("stack_state("), "list answers the derived stack state");
}
Expand Down
Loading