diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index 8d5cc0d5d0..b7b9ce14f2 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -1315,6 +1315,7 @@ fn cmd_claim(rest: &[String]) -> i32 { "lease-seconds", "lane", "task", + "count", "from-session", "platform", "session-id", @@ -1385,6 +1386,16 @@ fn cmd_claim(rest: &[String]) -> i32 { if let Some(task) = args.get_i64("task") { body["task_id"] = json!(task); } + // --count (#8217): batch claim — the broker runs the same + // atomic pick n times and answers with every claimed row. The + // cap is enforced here (local, instant) and broker-side. + let count = match batch_count_flag(args.get_i64("count")) { + Ok(c) => c, + Err(e) => die(2, &e), + }; + if count > 1 { + body["count"] = json!(count); + } // --from-session : with --task, a session-to-session // TRANSFER (#8210) — claim exactly this task DIRECTLY from // the session named, which must be the task's current holder @@ -1396,6 +1407,9 @@ fn cmd_claim(rest: &[String]) -> i32 { body["from_session"] = json!(fs); } let resp = unwrap_ok_fb(call_fb("/claim", &body), "/claim"); + if count > 1 { + return claim_batch_output(&resp, &worker, count); + } let (mut out, code) = claim_output(&resp); if code != 0 { eprint("repo-queue: no claimable task"); @@ -1504,6 +1518,138 @@ enum GuardOutcome { Unchecked(String), } +/// #8217: --count validation for the batch claim. Absent or 1 is +/// the ordinary single claim; 2..=BATCH_CLAIM_MAX is a batch; +/// anything else is a usage error, checked locally so the failure +/// is instant (the broker enforces the same bound). +fn batch_count_flag(n: Option) -> Result { + match n { + None => Ok(1), + Some(n) if n == 1 => Ok(1), + Some(n) if (2..=crate::turso_queue::BATCH_CLAIM_MAX).contains(&n) => Ok(n), + Some(n) => Err(format!( + "claim --count {n} is out of range: a batch claim takes \ + 1..={} items (#8217)", + crate::turso_queue::BATCH_CLAIM_MAX + )), + } +} + +/// The batch claim's response handling (#8217): the broker ran the +/// pick repeatedly and returned every claimed row. Each row goes +/// through the SAME per-item post-claim handling as a single +/// claim — the payload defense in depth and the #6741 +/// no-double-serve guard (a fallback-held row is blocked back, +/// never served) — then prints one verdict: +/// {"tasks": [...], "claimed": k, "requested": n, "guard_held": [...]}. +/// Zero served rows is the usual no-claim verdict (NO_CLAIM_EXIT). +fn claim_batch_output(resp: &Value, worker: &str, requested: i64) -> i32 { + let rows = resp + .get("rows") + .and_then(|r| r.as_array()) + .cloned() + .unwrap_or_default(); + let mut tasks: Vec = Vec::new(); + let mut held: Vec = Vec::new(); + for row in rows { + // Payload defense in depth, as in claim_output (#5444): a + // well-formed claim never carries a null or {} payload. + if let Some(payload) = row.get("payload") { + if payload.is_null() || payload.as_object().is_some_and(|o| o.is_empty()) { + continue; + } + } + match fallback_guard(&row, worker) { + GuardOutcome::HeldBy(holder) => { + let task_id = row.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + let (repo, issue) = task_issue(&row); + let blocker = format!( + "issue {repo}#{issue} is held in the GitHub fallback by {holder}; \ + primary-store claim auto-blocked to prevent double-serve (#6741)" + ); + let resp = call( + "/block", + &json!({ + "task_id": task_id, + "worker": worker, + "reason_class": "fallback_held", + "blocker": blocker, + "progress": {}, + }), + ); + if resp.get("ok").and_then(|o| o.as_bool()) == Some(false) { + eprint( + "repo-queue: WARNING: fallback guard block failed; \ + the task stays claimed under its lease", + ); + } + held.push(json!({ + "task": task_id, + "held_by": holder, + "repo": repo, + "issue": issue, + })); + } + GuardOutcome::Unchecked(e) => { + let mut row = row; + if let Some(o) = row.as_object_mut() { + o.insert( + "guard_warning".to_string(), + json!(format!( + "fallback double-serve guard could not check GitHub: {e}" + )), + ); + } + tasks.push(row); + } + GuardOutcome::Serve => tasks.push(row), + } + } + let claimed = tasks.len(); + print_json(&json!({ + "tasks": tasks, + "claimed": claimed, + "requested": requested, + "guard_held": held, + })); + if claimed == 0 { + eprint("repo-queue: no claimable task"); + return NO_CLAIM_EXIT; + } + 0 +} + +/// Release a claimed task straight back to the queue (#8217): +/// `release --worker --reason `. The broker +/// returns the row to `queued`, immediately claimable, and records +/// the reason on a `released` event. Dispatch uses it for an item +/// whose sub-task failed to launch or bind: the item goes back to +/// the pool in the same touch instead of sitting claimed and idle +/// until its lease expires. +fn cmd_release(rest: &[String]) -> i32 { + let args = parse_args(rest, &["worker", "reason"], &[]); + reject_extra_pos("release", &args, 1); + let Some(reason) = args.get("reason") else { + die( + 2, + "release requires --reason \"\" (#8217)", + ); + }; + if reason.trim().is_empty() { + die(2, "release requires a non-empty --reason (#8217)"); + } + let resp = unwrap_ok(call( + "/release", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "reason": reason, + }), + )); + print_json(&require_row(&resp, "release_repo_task")); + 0 +} + fn fallback_guard(row: &Value, my_worker: &str) -> GuardOutcome { let (repo, issue) = task_issue(row); if repo.is_empty() || issue <= 0 { @@ -2035,7 +2181,7 @@ fn atomic_write_json(path: &str, obj: &Value) { pub fn run(args: &[String]) -> i32 { if args.is_empty() { eprint( - "usage: repo-queue ...", + "usage: repo-queue ...", ); return 2; } @@ -2049,6 +2195,7 @@ pub fn run(args: &[String]) -> i32 { "enqueue" => cmd_enqueue(rest), "list" => cmd_list(rest), "claim" => cmd_claim(rest), + "release" => cmd_release(rest), "lane" => cmd_lane(rest), "bind" => cmd_bind(rest), "heartbeat" => cmd_heartbeat(rest), @@ -2113,6 +2260,22 @@ mod tests { assert!(platform_flag("").is_err()); } + #[test] + fn batch_count_flag_bounds_8217() { + // #8217: absent/1 = the single claim; 2..=cap = a batch; + // anything else is a usage error naming the cap. + assert_eq!(batch_count_flag(None), Ok(1)); + assert_eq!(batch_count_flag(Some(1)), Ok(1)); + assert_eq!(batch_count_flag(Some(2)), Ok(2)); + assert_eq!( + batch_count_flag(Some(crate::turso_queue::BATCH_CLAIM_MAX)), + Ok(crate::turso_queue::BATCH_CLAIM_MAX) + ); + assert!(batch_count_flag(Some(0)).is_err()); + assert!(batch_count_flag(Some(-3)).is_err()); + assert!(batch_count_flag(Some(crate::turso_queue::BATCH_CLAIM_MAX + 1)).is_err()); + } + #[test] fn fallback_switch_json_shape() { let v = fallback_switch_json("/claim", 4, "store down"); diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index d4ded47dbf..db0d0eaad2 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -2147,6 +2147,29 @@ fn claim_by_id( if let Some(reason) = claim_guard_reason(&row) { quarantine_task(t, task_id, &reason)?; return Ok(None); + // #8217: the plain by-id path honors the same recorded + // platform limitation the transfer claim enforces (#8210): + // an invalid (reason-less) stored limitation is cleared, + // never enforced; a valid one refuses a claim from any + // other family (or none) — the row simply reads unclaimable + // by id, like any other by-id refusal. + if let Some(ledger) = get_ledger(t, task_id)? { + let limit = ledger + .get("platform_limit") + .and_then(|v| v.as_str()); + let limit_reason = ledger + .get("platform_limit_reason") + .and_then(|v| v.as_str()); + if platform_limit_invalid(limit, limit_reason) { + t.exec( + "UPDATE repo_task_lane_ledger SET platform_limit = NULL, \ + platform_limit_reason = NULL, updated_at = ? WHERE task_id = ?", + &[Arg::Text(now_iso()), Arg::Int(task_id)], + )?; + } else if platform_limit_refusal(limit, limit_reason, family).is_some() { + return Ok(None); + } + } } let status = row .get("status") @@ -2245,6 +2268,27 @@ fn claim_by_id( /// and the caller re-picks — it can never be handed the winner's /// row. Extracted as a builder so the regression tests below pin /// the statement's shape without a live store. +/// The recorded platform limitation, expressed for the claim +/// pick (#8217, extending #8210's transfer-claim enforcement to +/// every pick): a row is unservable while its lane-ledger row +/// carries a VALID limitation — platform_limit and +/// platform_limit_reason both recorded (a reason-less stored +/// limitation is invalid: cleared, never enforced, exactly as +/// platform_limit_refusal treats it) — naming a family other +/// than the claim's declared family. A claim declaring no family +/// is served only unlimited rows. The two placeholders are the +/// claim's family, twice; callers append them after the pick +/// predicate's own arguments, in both the pick SELECT and the +/// claim UPDATE re-check. Semantics mirror +/// platform_limit_refusal's truth table (pinned by +/// platform_limit_pick_semantics_8217). +const PLATFORM_LIMIT_PICK_CLAUSE: &str = "AND NOT EXISTS (SELECT 1 FROM \ + repo_task_lane_ledger l WHERE l.task_id = tasks.id \ + AND l.platform_limit IS NOT NULL AND l.platform_limit <> '' \ + AND l.platform_limit_reason IS NOT NULL \ + AND l.platform_limit_reason <> '' \ + AND (? IS NULL OR l.platform_limit <> ?))"; + fn claim_update_sql(pick_predicate: &str) -> String { format!( "UPDATE tasks SET status = 'claimed', worker_id = ?, claimed_at = ?, \ @@ -2254,7 +2298,7 @@ fn claim_update_sql(pick_predicate: &str) -> String { park_kind = NULL, wait_kind = NULL, not_before = NULL, \ updated_at = ? \ WHERE id = ? \ - AND ( {pick_predicate} )" + AND ( {pick_predicate} ) {PLATFORM_LIMIT_PICK_CLAUSE}" ) } @@ -2508,6 +2552,299 @@ fn transfer_update_sql() -> &'static str { WHERE id = ? AND status = 'claimed' AND worker_id = ?" } +/// The claim preamble (#8217: shared by the single claim and +/// the batch claim): validate the caller's lane against the +/// registry, sweep expired leases, and quarantine payload-less +/// rows in this queue before any pick runs. +fn claim_preamble( + t: &TursoBackend, + queue: &str, + worker: &str, + lane: &Option, +) -> Result<(), TErr> { + if let Some(lane_id) = &lane { + let lanes = t.query_objs( + "SELECT lane_id, worker_id, queue, enabled FROM lanes WHERE lane_id = ?", + &[Arg::Text(lane_id.clone())], + &[], + )?; + let Some(l) = lanes.into_iter().next() else { + return Err(format!("claim_repo_task: unknown lane_id {lane_id}")); + }; + if l.get("worker_id").and_then(|v| v.as_str()) != Some(worker) { + return Err(format!( + "claim_repo_task: lane {lane_id} belongs to worker {}, not {worker}", + l.get("worker_id").and_then(|v| v.as_str()).unwrap_or("") + )); + } + if l.get("enabled").and_then(|v| v.as_i64()) == Some(0) { + return Err(format!("claim_repo_task: lane {lane_id} is disabled")); + } + if l.get("queue").and_then(|v| v.as_str()) != Some(queue) { + return Err(format!( + "claim_repo_task: lane {lane_id} is for queue {}, not {queue}", + l.get("queue").and_then(|v| v.as_str()).unwrap_or("") + )); + } + } + expire_leases(t)?; + quarantine_payload_missing(t, queue)?; + Ok(()) +} + +/// One pick-path claim: the atomic pick + the post-claim flow +/// (binding clear, lease row, model stamp, claimed event). +/// Extracted from verb_claim for #8217 so the batch claim runs +/// the identical pick N times; a single claim is exactly one +/// call of this. Returns the claimed row, or None when nothing +/// is eligible. +fn claim_pick_once( + t: &TursoBackend, + queue: String, + worker: String, + lane: &Option, + lease_seconds: i64, + family: Option, + claim_session: Option, + model: &Option, + handoff_pick: bool, +) -> Result, TErr> { + let now_unix = now_unix(); + let now = iso(now_unix); + let lease_until = claim_lease_until(now_unix, lease_seconds); + // One conditional UPDATE = the claim. The subquery picks the + // same row PG's SKIP LOCKED pick would (priority, then age; + // parked rows whose not_before has passed resume without an + // attempts increment); the outer status re-check keeps the + // statement atomic against a competing claim. + // #5444: the pick loops past rows the guard quarantines — + // a skipped row degrades to the next candidate or to no + // claim, never to a handed-out invalid packet. + let mut row: Value; + let mut id: i64; + let mut skipped = 0usize; + loop { + // #7617: pick the candidate id FIRST, then claim THAT row by + // id, and read it back by id. The previous shape claimed via + // a subquery and re-read the result as "the newest claimed + // row for (queue, worker_id)" — but every lane shares + // worker_id repo-worker-code, so under concurrent claims + // that re-read could return ANOTHER lane's just-claimed + // task: the caller was handed a row stamped with a foreign + // lane_id (live repro 2026-11-08: lane code-u claims + // returned tasks stamped code-e and code-t), it checkpointed + // and parked a task it did not own, and the guard below + // could quarantine a live foreign claim. The conditional + // UPDATE by id stays atomic: it re-checks the full pick + // eligibility (status, attempts cap, not_before) at claim + // instant, so if a competing claim takes the picked row + // first — or it is parked into the future in between — this + // UPDATE affects 0 rows and the loop re-picks. + // #8097: the pick predicate is built per pick mode. + // #8187: NEITHER mode filters by platform — the mark a + // claim declares (family) is stamped by the claim + // UPDATE, never matched against the item. The default mode keeps the ordinary predicate + // (queued rows due; parked rows whose timer has passed). + // Handoff mode picks the next parked recorded opencode + // handoff (PARKED_HANDOFF_SQL) with no caller-named id + // and no not_before gating — Rule 1's default collection + // path for the claimant. + let pick_predicate = if handoff_pick { + PARKED_HANDOFF_SQL.to_string() + } else { + default_pick_predicate() + }; + let pick_sql = format!( + "SELECT id FROM tasks WHERE queue = ? \ + AND payload IS NOT NULL AND payload <> '' AND payload <> '{{}}' \ + AND ( {pick_predicate} ) {PLATFORM_LIMIT_PICK_CLAUSE} \ + ORDER BY (priority IS NULL), priority ASC, created_at ASC LIMIT 1" + ); + let mut pick_args: Vec = vec![Arg::Text(queue.clone())]; + if !handoff_pick { + pick_args.push(Arg::Text(now.clone())); + pick_args.push(Arg::Text(now.clone())); + } + pick_args.push(arg_str(family.as_deref())); + pick_args.push(arg_str(family.as_deref())); + let pick = t.query_objs(&pick_sql, &pick_args, &[])?; + let Some(picked) = pick.into_iter().next() else { + return Ok(None); + }; + let pick_id = picked.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + let upd_sql = claim_update_sql(&pick_predicate); + let mut upd_args: Vec = vec![ + Arg::Text(worker.clone()), + Arg::Text(now.clone()), + Arg::Text(lease_until.clone()), + arg_str(lane.as_deref()), + arg_str(family.as_deref()), + Arg::Text(now.clone()), + Arg::Int(pick_id), + ]; + if !handoff_pick { + upd_args.push(Arg::Text(now.clone())); + upd_args.push(Arg::Text(now.clone())); + } + upd_args.push(arg_str(family.as_deref())); + upd_args.push(arg_str(family.as_deref())); + let upd = t.exec(&upd_sql, &upd_args)?; + if upd.affected == 0 { + // Lost the race for the picked row; re-pick. + skipped += 1; + if skipped >= 32 { + return Ok(None); + } + continue; + } + let rows = t.query_objs( + &format!("SELECT {TASK_COLS} FROM tasks WHERE id = ?"), + &[Arg::Int(pick_id)], + &TASK_JSON_COLS, + )?; + let Some(candidate) = rows.into_iter().next() else { + return Ok(None); + }; + if let Some(reason) = claim_guard_reason(&candidate) { + let cid = candidate.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + quarantine_task(t, cid, &reason)?; + skipped += 1; + if skipped >= 32 { + return Ok(None); + } + continue; + } + id = candidate.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + row = candidate; + break; + } + let mut row = row; + // Migration 0023 §4: a fresh claim never inherits a binding. + let progress = row.get("progress").cloned().unwrap_or(json!({})); + let (progress, cleared) = clear_binding(&progress, "claim_repo_task"); + if cleared.is_some() { + t.exec( + "UPDATE tasks SET progress = ? WHERE id = ?", + &[Arg::Text(progress.to_string()), Arg::Int(id)], + )?; + if let Some(obj) = row.as_object_mut() { + obj.insert("progress".to_string(), progress); + } + } + t.exec( + "INSERT INTO leases (task_id, worker_id, lease_until, heartbeat_at) \ + VALUES (?, ?, ?, ?) \ + ON CONFLICT(task_id) DO UPDATE SET worker_id = excluded.worker_id, \ + lease_until = excluded.lease_until, heartbeat_at = excluded.heartbeat_at", + &[ + Arg::Int(id), + Arg::Text(worker.clone()), + Arg::Text(lease_until), + Arg::Text(now_iso()), + ], + )?; + stamp_claim_model(t, id, &mut row, model)?; + touch_worker(t, &worker, Some(id))?; + if let Some(old) = &cleared { + on_binding_cleared(t, &worker, id, old, "claim_repo_task")?; + } + event( + t, + Some(&worker), + Some(id), + "claimed", + &with_marks( + &json!({ + "lease_seconds": lease_seconds, "via": "claim_repo_task_turso", + "cleared_session_id": cleared, "lane_id": lane, + "platform": family, "session_id": claim_session, + "model_provider": model.as_ref().map(|m| m.provider.clone()), + "model_id": model.as_ref().and_then(|m| m.model.clone()), + "model_variant": model.as_ref().and_then(|m| m.variant.clone()), + "pick": if handoff_pick { "parked_handoff" } else { "default" }, + }), + &row, + ), + )?; + Ok(Some(row)) +} + +/// The most tasks one batch claim may take (#8217). A batch is +/// only legitimate paired with immediate per-item dispatch, and +/// the dispatcher must launch + verify-bind every item inside one +/// touch before leases age: five dedicated launches fit that +/// window with margin, and a bigger batch would recreate the +/// claimed-and-idle pile the single-session design forbids. +pub const BATCH_CLAIM_MAX: i64 = 5; + +/// Parse a claim request's batch count (#8217): absent means the +/// single claim (1); anything outside 1..=BATCH_CLAIM_MAX is a +/// usage error, never a silent clamp. +fn parse_batch_count(req: &Value) -> Result { + match req_i64(req, "count") { + None => Ok(1), + Some(n) if (1..=BATCH_CLAIM_MAX).contains(&n) => Ok(n), + Some(n) => Err(format!( + "count {n} is out of range: a batch claim takes 1..={BATCH_CLAIM_MAX} items (#8217)" + )), + } +} + +/// Batch claim (#8217): the claim preamble once, then the +/// identical atomic pick up to `count` times — same eligibility, +/// same priority/age order, same attempts/lease semantics and +/// per-item claimed events as that many single claims. A partial +/// batch is normal: the loop stops at the first no-task pick and +/// returns what exists. +#[allow(clippy::too_many_arguments)] +fn verb_claim_batch( + t: &TursoBackend, + queue: &str, + worker: &str, + lane: &Option, + lease_seconds: i64, + family: &Option, + claim_session: &Option, + model: &Option, + handoff_pick: bool, + count: i64, +) -> Value { + let work = (|| -> Result, TErr> { + claim_preamble(t, queue, worker, lane)?; + let mut rows = Vec::new(); + for _ in 0..count { + let Some(row) = claim_pick_once( + t, + queue.to_string(), + worker.to_string(), + lane, + lease_seconds, + family.clone(), + claim_session.clone(), + model, + handoff_pick, + )? + else { + break; + }; + rows.push(row); + } + Ok(rows) + })(); + match work { + Ok(rows) => { + let claimed = rows.len(); + ok(json!({ + "rows": rows, + "claimed": claimed, + "requested": count, + })) + } + Err(e) if e.starts_with("claim_repo_task:") => fail(4, e), + Err(e) => terr(e), + } +} + fn verb_claim(t: &TursoBackend, req: &Value) -> Value { let worker = req_str(req, "worker").unwrap_or("").to_string(); let queue = req_str(req, "queue").unwrap_or("").to_string(); @@ -2545,34 +2882,40 @@ fn verb_claim(t: &TursoBackend, req: &Value) -> Value { return fail(2, format!("claim_repo_task: unknown pick mode {other:?}")); } }; - let work = (|| -> Result, TErr> { - if let Some(lane_id) = &lane { - let lanes = t.query_objs( - "SELECT lane_id, worker_id, queue, enabled FROM lanes WHERE lane_id = ?", - &[Arg::Text(lane_id.clone())], - &[], - )?; - let Some(l) = lanes.into_iter().next() else { - return Err(format!("claim_repo_task: unknown lane_id {lane_id}")); - }; - if l.get("worker_id").and_then(|v| v.as_str()) != Some(worker.as_str()) { - return Err(format!( - "claim_repo_task: lane {lane_id} belongs to worker {}, not {worker}", - l.get("worker_id").and_then(|v| v.as_str()).unwrap_or("") - )); - } - if l.get("enabled").and_then(|v| v.as_i64()) == Some(0) { - return Err(format!("claim_repo_task: lane {lane_id} is disabled")); - } - if l.get("queue").and_then(|v| v.as_str()) != Some(queue.as_str()) { - return Err(format!( - "claim_repo_task: lane {lane_id} is for queue {}, not {queue}", - l.get("queue").and_then(|v| v.as_str()).unwrap_or("") - )); - } + // #8217: batch claim. `count` absent or 1 is the single claim + // below, byte for byte. count > 1 runs the same pick that many + // times (verb_claim_batch) and returns every claimed row; it + // never combines with a named task (by-id and transfer claims + // take exactly one row). + let count = match parse_batch_count(req) { + Ok(c) => c, + Err(e) => return fail(2, format!("claim_repo_task: {e}")), + }; + if count > 1 { + if req_i64(req, "task_id").is_some() { + return fail( + 2, + "claim_repo_task: --count cannot be combined with --task: \ + a by-id claim takes exactly one task (#8217)" + .to_string(), + ); } - expire_leases(t)?; - quarantine_payload_missing(t, &queue)?; + return verb_claim_batch( + t, + &queue, + &worker, + &lane, + lease_seconds, + &family, + &claim_session, + &model, + handoff_pick, + count, + ); + } + + let work = (|| -> Result, TErr> { + claim_preamble(t, &queue, &worker, &lane)?; // By-id claim — the SPECIAL CASE (#8097 Rule 1): when the // request names a task, take exactly that row (claim_by_id) // instead of the pick. Reserved for one-off revivals of a @@ -2609,160 +2952,17 @@ fn verb_claim(t: &TursoBackend, req: &Value) -> Value { &model, ); } - let now_unix = now_unix(); - let now = iso(now_unix); - let lease_until = claim_lease_until(now_unix, lease_seconds); - // One conditional UPDATE = the claim. The subquery picks the - // same row PG's SKIP LOCKED pick would (priority, then age; - // parked rows whose not_before has passed resume without an - // attempts increment); the outer status re-check keeps the - // statement atomic against a competing claim. - // #5444: the pick loops past rows the guard quarantines — - // a skipped row degrades to the next candidate or to no - // claim, never to a handed-out invalid packet. - let mut row: Value; - let mut id: i64; - let mut skipped = 0usize; - loop { - // #7617: pick the candidate id FIRST, then claim THAT row by - // id, and read it back by id. The previous shape claimed via - // a subquery and re-read the result as "the newest claimed - // row for (queue, worker_id)" — but every lane shares - // worker_id repo-worker-code, so under concurrent claims - // that re-read could return ANOTHER lane's just-claimed - // task: the caller was handed a row stamped with a foreign - // lane_id (live repro 2026-11-08: lane code-u claims - // returned tasks stamped code-e and code-t), it checkpointed - // and parked a task it did not own, and the guard below - // could quarantine a live foreign claim. The conditional - // UPDATE by id stays atomic: it re-checks the full pick - // eligibility (status, attempts cap, not_before) at claim - // instant, so if a competing claim takes the picked row - // first — or it is parked into the future in between — this - // UPDATE affects 0 rows and the loop re-picks. - // #8097: the pick predicate is built per pick mode. - // #8187: NEITHER mode filters by platform — the mark a - // claim declares (family) is stamped by the claim - // UPDATE, never matched against the item. The default mode keeps the ordinary predicate - // (queued rows due; parked rows whose timer has passed). - // Handoff mode picks the next parked recorded opencode - // handoff (PARKED_HANDOFF_SQL) with no caller-named id - // and no not_before gating — Rule 1's default collection - // path for the claimant. - let pick_predicate = if handoff_pick { - PARKED_HANDOFF_SQL.to_string() - } else { - default_pick_predicate() - }; - let pick_sql = format!( - "SELECT id FROM tasks WHERE queue = ? \ - AND payload IS NOT NULL AND payload <> '' AND payload <> '{{}}' \ - AND ( {pick_predicate} ) \ - ORDER BY (priority IS NULL), priority ASC, created_at ASC LIMIT 1" - ); - let mut pick_args: Vec = vec![Arg::Text(queue.clone())]; - if !handoff_pick { - pick_args.push(Arg::Text(now.clone())); - pick_args.push(Arg::Text(now.clone())); - } - let pick = t.query_objs(&pick_sql, &pick_args, &[])?; - let Some(picked) = pick.into_iter().next() else { - return Ok(None); - }; - let pick_id = picked.get("id").and_then(|v| v.as_i64()).unwrap_or(0); - let upd_sql = claim_update_sql(&pick_predicate); - let mut upd_args: Vec = vec![ - Arg::Text(worker.clone()), - Arg::Text(now.clone()), - Arg::Text(lease_until.clone()), - arg_str(lane.as_deref()), - arg_str(family.as_deref()), - Arg::Text(now.clone()), - Arg::Int(pick_id), - ]; - if !handoff_pick { - upd_args.push(Arg::Text(now.clone())); - upd_args.push(Arg::Text(now.clone())); - } - let upd = t.exec(&upd_sql, &upd_args)?; - if upd.affected == 0 { - // Lost the race for the picked row; re-pick. - skipped += 1; - if skipped >= 32 { - return Ok(None); - } - continue; - } - let rows = t.query_objs( - &format!("SELECT {TASK_COLS} FROM tasks WHERE id = ?"), - &[Arg::Int(pick_id)], - &TASK_JSON_COLS, - )?; - let Some(candidate) = rows.into_iter().next() else { - return Ok(None); - }; - if let Some(reason) = claim_guard_reason(&candidate) { - let cid = candidate.get("id").and_then(|v| v.as_i64()).unwrap_or(0); - quarantine_task(t, cid, &reason)?; - skipped += 1; - if skipped >= 32 { - return Ok(None); - } - continue; - } - id = candidate.get("id").and_then(|v| v.as_i64()).unwrap_or(0); - row = candidate; - break; - } - let mut row = row; - // Migration 0023 §4: a fresh claim never inherits a binding. - let progress = row.get("progress").cloned().unwrap_or(json!({})); - let (progress, cleared) = clear_binding(&progress, "claim_repo_task"); - if cleared.is_some() { - t.exec( - "UPDATE tasks SET progress = ? WHERE id = ?", - &[Arg::Text(progress.to_string()), Arg::Int(id)], - )?; - if let Some(obj) = row.as_object_mut() { - obj.insert("progress".to_string(), progress); - } - } - t.exec( - "INSERT INTO leases (task_id, worker_id, lease_until, heartbeat_at) \ - VALUES (?, ?, ?, ?) \ - ON CONFLICT(task_id) DO UPDATE SET worker_id = excluded.worker_id, \ - lease_until = excluded.lease_until, heartbeat_at = excluded.heartbeat_at", - &[ - Arg::Int(id), - Arg::Text(worker.clone()), - Arg::Text(lease_until), - Arg::Text(now_iso()), - ], - )?; - stamp_claim_model(t, id, &mut row, &model)?; - touch_worker(t, &worker, Some(id))?; - if let Some(old) = &cleared { - on_binding_cleared(t, &worker, id, old, "claim_repo_task")?; - } - event( + claim_pick_once( t, - Some(&worker), - Some(id), - "claimed", - &with_marks( - &json!({ - "lease_seconds": lease_seconds, "via": "claim_repo_task_turso", - "cleared_session_id": cleared, "lane_id": lane, - "platform": family, "session_id": claim_session, - "model_provider": model.as_ref().map(|m| m.provider.clone()), - "model_id": model.as_ref().and_then(|m| m.model.clone()), - "model_variant": model.as_ref().and_then(|m| m.variant.clone()), - "pick": if handoff_pick { "parked_handoff" } else { "default" }, - }), - &row, - ), - )?; - Ok(Some(row)) + queue.clone(), + worker.clone(), + &lane, + lease_seconds, + family, + claim_session, + &model, + handoff_pick, + ) })(); match work { Ok(Some(row)) => ok(json!({"row": row})), @@ -3392,6 +3592,71 @@ fn wake_eligible(status: &str) -> Result<(), String> { /// next claim is an ordinary execution claim. This replaces the /// lanes' 25-minute re-check loop as the wake path for recorded /// waits: the park TTL floor is only the backstop. +/// Release a claimed task straight back to queued (#8217): the +/// holder gives the item back to the pool NOW — no park timer, no +/// attempt change (the claim happened; the `released` event +/// carries the reason, and revive remains the cap-repair tool). +/// Holder-only, through the same claimed_by guard as checkpoint. +/// This is the dispatch failure path: an item whose sub-task +/// session failed to launch/bind returns to the pool immediately +/// instead of sitting claimed-idle under the dispatcher. +fn verb_release(t: &TursoBackend, req: &Value) -> Value { + let task_id = req_i64(req, "task_id").unwrap_or(0); + let worker = req_str(req, "worker").unwrap_or("").to_string(); + let reason = req_str(req, "reason").unwrap_or("").to_string(); + if reason.trim().is_empty() { + return fail( + 2, + "release_repo_task: a release requires a reason (--reason): the audit event is the only record of why the item went back" + .to_string(), + ); + } + let row = match claimed_by(t, task_id, &worker, "release_repo_task") { + Ok(r) => r, + Err(v) => return v, + }; + let work = (|| -> Result { + // A released claim never leaves a binding behind + // (migration 0023 §4's rule, mirrored from the claim path). + let progress = row.get("progress").cloned().unwrap_or(json!({})); + let (progress, cleared) = clear_binding(&progress, "release_repo_task"); + t.exec( + "UPDATE tasks SET status = 'queued', worker_id = NULL, \ + lease_until = NULL, not_before = NULL, park_kind = NULL, \ + wait_kind = NULL, progress = ?, updated_at = ? \ + WHERE id = ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + t.exec("DELETE FROM leases WHERE task_id = ?", &[Arg::Int(task_id)])?; + touch_worker(t, &worker, Some(task_id))?; + if let Some(old) = &cleared { + on_binding_cleared(t, &worker, task_id, old, "release_repo_task")?; + } + event( + t, + Some(&worker), + Some(task_id), + "released", + &with_marks( + &json!({ + "reason": reason, "via": "release_repo_task_turso", + "cleared_session_id": cleared, + }), + &row, + ), + )?; + get_task(t, task_id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) => ok(json!({ "row": row })), + Err(e) => terr(e), + } +} + fn verb_wake(t: &TursoBackend, req: &Value) -> Value { let task_id = req_i64(req, "task_id").unwrap_or(0); let worker = req_str(req, "worker") @@ -4164,6 +4429,7 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/heartbeat" => verb_heartbeat(t, req), "/checkpoint" => verb_checkpoint(t, req), "/park" => verb_park(t, req), + "/release" => verb_release(t, req), "/wake" => verb_wake(t, req), "/block" => verb_block(t, req), "/cancel" => verb_cancel(t, req), @@ -5455,4 +5721,163 @@ mod tests { prop_assert_eq!(issue_number_from_dedupe(&key, "developing-today/code"), None); } } + + // ---- #8217: batch claim, platform limitation in the pick, + // ---- and the release verb ---- + + fn seg8217<'a>(src: &'a str, from: &str, to: &str) -> &'a str { + src.split(from) + .nth(1) + .unwrap_or("") + .split(to) + .next() + .unwrap_or("") + } + + #[test] + fn batch_count_parsing_and_cap_8217() { + // The cap is a named constant with the reasoning on #8217: + // one batch = one lane touch = one supervisor. + assert_eq!(BATCH_CLAIM_MAX, 5); + assert_eq!(parse_batch_count(&json!({})), Ok(1)); + assert_eq!(parse_batch_count(&json!({"count": 1})), Ok(1)); + assert_eq!(parse_batch_count(&json!({"count": 3})), Ok(3)); + assert_eq!( + parse_batch_count(&json!({"count": BATCH_CLAIM_MAX})), + Ok(BATCH_CLAIM_MAX) + ); + let over = parse_batch_count(&json!({"count": BATCH_CLAIM_MAX + 1})).unwrap_err(); + assert!(over.contains("out of range") && over.contains("1..=5"), "{over}"); + assert!(parse_batch_count(&json!({"count": 0})).is_err()); + assert!(parse_batch_count(&json!({"count": -2})).is_err()); + } + + #[test] + fn batch_claim_response_shape_8217() { + // The batch verb's wire shape: the claimed rows in pick + // order, how many were claimed, how many were requested — + // a short batch is a normal partial success, and an empty + // one is the usual no-task verdict on the client. + let rows = vec![json!({"id": 11}), json!({"id": 7}), json!({"id": 42})]; + let out = json!({"rows": rows, "claimed": 3, "requested": 5}); + assert_eq!(out["claimed"], json!(3)); + assert_eq!(out["requested"], json!(5)); + let ids: Vec = out["rows"] + .as_array() + .unwrap() + .iter() + .map(|r| r["id"].as_i64().unwrap()) + .collect(); + assert_eq!(ids, vec![11, 7, 42], "rows keep pick order"); + } + + #[test] + fn batch_claim_runs_the_single_pick_repeatedly_8217() { + // Oracle: the batch verb is a loop over claim_pick_once + // (the single claim's pick — same eligibility, same order, + // same per-item lease, marks and claimed event) behind ONE + // claim_preamble, and the single claim routes count > 1 to + // it while refusing the by-id combination. + let src = include_str!("turso_queue.rs"); + let batch = seg8217(src, "fn verb_claim_batch(", "\nfn verb_claim("); + assert!(batch.contains("claim_preamble("), "one preamble per batch"); + assert!( + batch.contains("claim_pick_once("), + "batch = the single pick, repeated" + ); + assert!(batch.contains("\"rows\": rows"), "batch returns the claimed set"); + let single = seg8217(src, "fn verb_claim(", "\nfn verb_bind("); + assert!(single.contains("count > 1"), "single claim routes batches"); + assert!( + single.contains("cannot be combined with --task"), + "by-id and transfer claims stay single" + ); + assert!( + single.contains("claim_preamble(") && single.contains("claim_pick_once("), + "single claim is one preamble + one pick" + ); + } + + #[test] + fn platform_limit_pick_clause_shape_8217() { + // The clause consults the lane ledger and skips only rows + // with a VALID stored limitation (a recorded reason) + // naming the OTHER family; reason-less rows are not + // limitations (Drew's rule: no reason, no limitation). + for needle in [ + "repo_task_lane_ledger", + "platform_limit IS NOT NULL", + "platform_limit_reason IS NOT NULL", + "platform_limit_reason <> ''", + "(? IS NULL OR", + ] { + assert!( + PLATFORM_LIMIT_PICK_CLAUSE.contains(needle), + "clause misses {needle}" + ); + } + // Both pick statements carry the clause after the + // eligibility predicate, with the claim's family bound + // twice: 7 fixed placeholders + 2 predicate + 2 clause. + let upd = claim_update_sql(&default_pick_predicate()); + assert!( + upd.contains("AND NOT EXISTS (SELECT 1 FROM repo_task_lane_ledger"), + "{upd}" + ); + assert_eq!(upd.matches('?').count(), 11, "claim UPDATE bindings: {upd}"); + let src = include_str!("turso_queue.rs"); + let pick = seg8217(src, "fn claim_pick_once(", "\nfn parse_batch_count("); + assert_eq!( + pick.matches("pick_args.push(arg_str(family.as_deref()))").count(), + 2, + "candidate SELECT binds the family twice" + ); + assert_eq!( + pick.matches("upd_args.push(arg_str(family.as_deref()))").count(), + 2, + "claim UPDATE binds the family twice" + ); + } + + #[test] + fn claim_by_id_enforces_platform_limit_like_the_pick_8217() { + // Oracle: a plain by-id claim refuses a cross-family valid + // limitation (the row reads as not claimable) and CLEARS a + // reason-less stored one instead of enforcing it. + let src = include_str!("turso_queue.rs"); + let seg = seg8217(src, "fn claim_by_id(", "\nfn claim_transfer("); + assert!( + seg.contains("platform_limit_refusal("), + "by-id claim enforces the limitation" + ); + assert!( + seg.contains("platform_limit = NULL") + && seg.contains("platform_limit_reason = NULL"), + "an invalid stored limit is cleared, not enforced" + ); + } + + #[test] + fn release_verb_contract_8217() { + // Oracle: release is holder-checked and reason-required, + // and returns the row to `queued` with its lease and + // session binding cleared and a `released` audit event; + // attempts are NOT handed back. + let src = include_str!("turso_queue.rs"); + let seg = seg8217(src, "/// Release a claimed task straight back", "\nfn verb_park("); + for needle in [ + "a release requires a reason", + "claimed_by(", + "\"released\"", + "DELETE FROM leases", + "attempt change", + "SET status = 'queued'", + ] { + assert!(seg.contains(needle), "verb_release misses {needle}"); + } + assert!( + src.contains("\"/release\" => verb_release(t, req),"), + "release is dispatched" + ); + } } diff --git a/pm-stack/opencode-claimant/dispatch_batch.py b/pm-stack/opencode-claimant/dispatch_batch.py new file mode 100644 index 0000000000..d1b4206644 --- /dev/null +++ b/pm-stack/opencode-claimant/dispatch_batch.py @@ -0,0 +1,451 @@ +#!/usr/bin/env python3 +"""dispatch_batch.py — batch claim + per-item dedicated sub-task dispatch (#8217). + +One call a Muse lane makes to run part of a bundle in DISPATCH +mode: batch-claim up to the broker cap, then hand EVERY claimed item +to its own dedicated sub-task session inside the same touch: + + python3 -I dispatch_batch.py --queue --count \ + --to opencode|Muse --worker --lane \ + --reason "" \ + --notes "" \ + [--session-id ] \ + [--bind : ...] [--release-failures] \ + [--lease-seconds ] [--dry-run] + +Serial single-session work stays the queue's default (#8187); +dispatch mode is an allowed STATED mode. The batch reason is the +lane's stated reason for dispatching rather than working the items +itself, and it is recorded on every item (the assignment event for +opencode items, a dispatch checkpoint for Muse items). + +Flow: + 1. ONE batch claim (`repo-queue claim --count N --platform + `). The claim declares the family that will + WORK the items, so a task carrying a recorded platform + limitation (lane ledger, #8210: limit + reason) is never + served into the wrong family's batch — the broker's pick + enforces the limitation; a family-less claim is served only + unlimited rows. + 2. Per item, in claim order: + - its own worktree on the laptop, per runbook SS3 + (~/git/fleet/queue---dispatch, branch + queue/--dispatch) — created here, never the + primary checkout, never shared between items; + - opencode: send_to_opencode.py's send() — records the + opencode assignment WITH the batch reason, checkpoints the + pass, creates the session IN the worktree, transfers the + claim from the dispatching session with no queued/parked + stop, and sends the prompt carrying the lane's notes; + - Muse: the assignment stays direct (lane verb), the batch + reason + notes + worktree are checkpointed on the item, and + the item is bound to the dedicated Muse sub-session the + lane spawned for it (`--bind :` — the lane + spawns the sub-session with its own machinery, then this + tool binds + verifies it; an item with no --bind is + reported `prepared_unbound` and fails the batch: the lane + must not let go of an unbound item). + 3. Every bind is VERIFIED from live queue state (the task's + progress.session_id equals the launched/bound session id) + before the batch ends. + 4. An item that fails to launch/bind is never left claimed-idle: + the send's own rollback leaves the assignment direct under + the dispatching lane's still-live claim (outcome + `held_by_lane_direct` — its owner is present and works it + serially), or with --release-failures it is released straight + back to queued via `repo-queue release` with the failure as + the release reason. + +Output: one JSON record per item plus a summary record, printed to +stdout; exit 0 only when every item is bound (or, in --dry-run, +would be). The claim itself is the broker's: `claim --count` runs +the ordinary atomic pick N times (same eligibility, same +priority/age order, same per-item events and marks). +""" + +import argparse +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def _load_sibling(name): + """Load poll.py / claimant.py / launch_one.py / + send_to_opencode.py from this file's own directory — the + sibling in THIS checkout, as launch_one loads its siblings.""" + spec = importlib.util.spec_from_file_location( + f"dispatch_{name}", HERE / f"{name}.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +poll = _load_sibling("poll") +claimant = _load_sibling("claimant") +launch_one = _load_sibling("launch_one") +send_mod = _load_sibling("send_to_opencode") + +REPOS = launch_one.REPOS +BATCH_MAX = 5 # mirrors the broker's BATCH_CLAIM_MAX (#8217) +FLEET_WORKTREE_ROOT = Path.home() / "git" / "fleet" +TARGET_FAMILY = {"opencode": "openchamber", "Muse": "muse"} + + +# --- seams (patched by tests) ------------------------------------------------ + +def queue(*args, timeout=120): + """Run a repo-queue verb through launch_one's runner.""" + return launch_one.queue(*args, timeout=timeout) + + +def queue_json(*args, timeout=120): + """repo-queue verb -> (rc, parsed_json_or_None, stderr).""" + rc, out, err = queue(*args, timeout=timeout) + data = None + if out and out.strip(): + try: + data = json.loads(out) + except ValueError: + data = None + return rc, data, err + + +def run_send(queue_name, task_id, worker, from_session, reason, + notes, worktree): + """One opencode send via send_to_opencode.send() — the #8210 + launcher, reused whole (no third launcher). Returns its record.""" + return send_mod.send(queue_name, task_id, worker, from_session, + reason, notes, worktree) + + +def fetch_task_row(queue_name, task_id): + """The task's current row from the broker's rich list (claimed + rows first, then queued — a released item reads back queued).""" + for status in ("claimed", "queued", "parked"): + try: + data = poll._broker_post( + "/list", {"queue": queue_name, "status": status, + "rich": True, "limit": 500}) + except Exception: + continue + rows = data.get("rows") if isinstance(data, dict) else data + for row in rows or []: + if isinstance(row, dict) and row.get("id") == task_id: + return poll.normalize_row(row) + return None + + +def git(primary, *args, timeout=120): + p = subprocess.run(["git", "-C", str(primary), *args], + capture_output=True, text=True, timeout=timeout) + return p.returncode, p.stdout.strip(), p.stderr.strip() + + +# --- worktrees --------------------------------------------------------------- + +def worktree_for(primary, task_id, issue): + """The item's dedicated worktree (runbook SS3 naming): + ~/git/fleet/queue---dispatch on branch + queue/--dispatch. Created when missing; an + existing dir must already be a worktree of the primary.""" + name = f"queue-{task_id}-{issue}-dispatch" + path = FLEET_WORKTREE_ROOT / name + branch = f"queue/{task_id}-{issue}-dispatch" + if path.exists(): + rc, out, _ = git(primary, "worktree", "list", "--porcelain") + known = {ln.split()[1] for ln in out.splitlines() + if ln.startswith("worktree ")} if rc == 0 else set() + if str(path) in known: + return str(path), False, None + return None, False, f"{path} exists but is not a worktree of {primary}" + FLEET_WORKTREE_ROOT.mkdir(parents=True, exist_ok=True) + rc, _out, err = git(primary, "worktree", "add", "-b", branch, + str(path), "main") + if rc != 0: + # Branch may already exist from a prior dispatch of this + # task: attach it instead of failing. + rc2, _o2, err2 = git(primary, "worktree", "add", str(path), branch) + if rc2 != 0: + return None, False, f"git worktree add failed: {err or err2}" + return str(path), True, None + + +# --- batch claim ------------------------------------------------------------- + +def claim_batch(queue_name, worker, lane, count, family, + session_id, lease_seconds): + """The broker batch claim. Returns (rows, error).""" + args = ["claim", "--queue", queue_name, "--worker", worker, + "--count", str(count), "--platform", family, + "--lease-seconds", str(lease_seconds)] + if lane: + args += ["--lane", lane] + if session_id: + args += ["--session-id", session_id] + rc, data, err = queue_json(*args) + if data is None: + return [], f"batch claim unparseable (rc={rc}): {err.strip()[:200]}" + tasks = data.get("tasks") + if not isinstance(tasks, list): + return [], f"batch claim returned no tasks array: {str(data)[:200]}" + return tasks, None + + +def release_task(task_id, worker, reason): + rc, _data, err = queue_json( + "release", str(task_id), "--worker", worker, + "--reason", reason) + return rc == 0, err.strip()[:200] + + +def lane_direct(task_id, worker): + rc, _data, err = queue_json("lane", str(task_id), "--worker", worker) + return rc == 0, err.strip()[:200] + + +def checkpoint(task_id, worker, stage, progress): + rc, _data, err = queue_json( + "checkpoint", str(task_id), "--worker", worker, + "--stage", stage, "--progress", json.dumps(progress)) + return rc == 0, err.strip()[:200] + + +def bind_session(task_id, worker, session_id): + rc, _data, err = queue_json( + "bind", str(task_id), "--worker", worker, + "--session-id", session_id, "--launched-by", worker) + return rc == 0, err.strip()[:200] + + +def bound_session_id(queue_name, task_id): + row = fetch_task_row(queue_name, task_id) + if not row: + return None, None + progress = row.get("progress") or {} + return progress.get("session_id"), row + + +# --- per-item dispatch ------------------------------------------------------- + +def dispatch_opencode_item(queue_name, row, worker, from_session, + reason, notes, release_failures): + task_id = row["id"] + ref = task_ref(row) + primary = REPOS[queue_name][1] + rec = {"task": task_id, "target": "opencode", "issue": ref[1] if ref else None} + worktree, created, werr = worktree_for(primary, task_id, rec["issue"] or 0) + if werr: + return fail_item(rec, "worktree", werr, row, worker, release_failures) + rec["worktree"] = worktree + rec["worktree_created"] = created + srec = run_send(queue_name, task_id, worker, from_session, + reason, notes, worktree) + if not srec or not srec.get("ok"): + why = (srec or {}).get("reason") or "send failed" + phase = (srec or {}).get("phase") or "send" + return fail_item(rec, phase, str(why), row, worker, + release_failures) + sid = srec.get("session_id") + rec["session_id"] = sid + bound, _row2 = bound_session_id(queue_name, task_id) + if bound != sid: + return fail_item( + rec, "verify", + f"bind not visible in live queue state (want {sid}, read {bound})", + row, worker, release_failures) + rec["ok"] = True + rec["outcome"] = "bound" + return rec + + +def dispatch_claude_item(queue_name, row, worker, reason, notes, + binds, release_failures): + task_id = row["id"] + ref = task_ref(row) + primary = REPOS[queue_name][1] + rec = {"task": task_id, "target": "Muse", "issue": ref[1] if ref else None} + worktree, created, werr = worktree_for(primary, task_id, rec["issue"] or 0) + if werr: + return fail_item(rec, "worktree", werr, row, worker, release_failures) + rec["worktree"] = worktree + rec["worktree_created"] = created + ok_lane, lerr = lane_direct(task_id, worker) + if not ok_lane: + return fail_item(rec, "lane", lerr, row, worker, release_failures) + ok_cp, cperr = checkpoint( + task_id, worker, "dispatched", + {"dispatch_mode": "batch", "dispatch_reason": reason, + "worktree": worktree, "notes": notes, + "target": "Muse"}) + if not ok_cp: + return fail_item(rec, "checkpoint", cperr, row, worker, + release_failures) + sid = binds.get(task_id) + if not sid: + rec["ok"] = False + rec["outcome"] = "prepared_unbound" + rec["reason"] = ("no --bind : for this item: " + "the lane must spawn its dedicated sub-session " + "and bind it before letting go") + rec["bind_command"] = ( + f"fleet queue bind {task_id} --worker {worker} " + f"--session-id ") + return rec + ok_bind, berr = bind_session(task_id, worker, sid) + if not ok_bind: + return fail_item(rec, "bind", berr, row, worker, release_failures) + bound, _row2 = bound_session_id(queue_name, task_id) + if bound != sid: + return fail_item( + rec, "verify", + f"bind not visible in live queue state (want {sid}, read {bound})", + row, worker, release_failures) + rec["session_id"] = sid + rec["ok"] = True + rec["outcome"] = "bound" + return rec + + +def fail_item(rec, phase, why, row, worker, release_failures): + """A failed item is never left claimed-idle: release it back to + queued when asked, else it stays under the dispatching lane's + live claim with a direct assignment (held_by_lane_direct).""" + rec["ok"] = False + rec["phase"] = phase + rec["reason"] = why + if release_failures: + ok_rel, rerr = release_task( + rec["task"], worker, + f"dispatch failed ({phase}: {why}); released by " + f"dispatch_batch (#8217)") + rec["outcome"] = "released_to_queue" if ok_rel else "release_failed" + if not ok_rel: + rec["release_error"] = rerr + else: + rec["outcome"] = "held_by_lane_direct" + return rec + + +def task_ref(row): + """(repo, issue_number) from a claimed row's payload, or None.""" + payload = row.get("payload") or {} + repo = payload.get("repo") + issue = (payload.get("issue") or {}).get("number") + if repo and issue: + return repo, issue + return None + + +# --- main -------------------------------------------------------------------- + +def dispatch(queue_name, count, target, worker, lane, reason, notes, + session_id, binds, release_failures, lease_seconds, + dry_run=False): + family = TARGET_FAMILY[target] + rows, err = claim_batch(queue_name, worker, lane, count, family, + session_id, lease_seconds) + if err: + return [{"kind": "dispatch_batch", "ok": False, + "phase": "claim", "reason": err}], False + if not rows: + return [{"kind": "dispatch_batch", "ok": False, + "phase": "claim", + "reason": "no claimable task for this batch"}], False + summary = {"kind": "dispatch_batch", "queue": queue_name, + "target": target, "family": family, + "requested": count, "claimed": len(rows), + "reason": reason} + if dry_run: + summary["ok"] = True + summary["dry_run"] = True + summary["tasks"] = [r.get("id") for r in rows] + return [summary], True + records = [summary] + all_ok = True + for row in rows: + if target == "opencode": + rec = dispatch_opencode_item( + queue_name, row, worker, session_id, reason, notes, + release_failures) + else: + rec = dispatch_claude_item( + queue_name, row, worker, reason, notes, binds, + release_failures) + records.append(rec) + all_ok = all_ok and bool(rec.get("ok")) + summary["ok"] = all_ok + summary["bound"] = sum(1 for r in records[1:] + if r.get("outcome") == "bound") + return records, all_ok + + +def main(argv): + ap = argparse.ArgumentParser( + description="Batch claim + per-item dedicated sub-task " + "dispatch (#8217).") + ap.add_argument("--queue", required=True, choices=sorted(REPOS)) + ap.add_argument("--count", type=int, required=True) + ap.add_argument("--to", required=True, + choices=sorted(TARGET_FAMILY), dest="target") + ap.add_argument("--worker", required=True, + help="the dispatching lane's queue worker id") + ap.add_argument("--lane", help="the dispatching lane id") + ap.add_argument("--reason", required=True, + help="the stated batch dispatch reason, recorded " + "on every item") + ap.add_argument("--notes", default="", + help="the lane's notes, carried into every item") + ap.add_argument("--session-id", + help="the dispatching session's own id (the " + "holder mark the opencode transfer names)") + ap.add_argument("--bind", action="append", default=[], + metavar="TASK:SESSION", + help="for --to Muse: the dedicated sub-session " + "id the lane spawned for that task") + ap.add_argument("--release-failures", action="store_true", + help="release failed items back to queued " + "instead of leaving them with the lane") + ap.add_argument("--lease-seconds", type=int, default=2700) + ap.add_argument("--dry-run", action="store_true", + help="claim the batch and report it, dispatch " + "nothing (items stay the lane's own claim)") + args = ap.parse_args(argv[1:]) + + if not (1 <= args.count <= BATCH_MAX): + print(json.dumps({"ok": False, "phase": "validate", + "reason": f"--count must be 1..{BATCH_MAX} " + f"(the batch cap, #8217)"})) + return 2 + if args.target == "opencode" and not args.session_id: + print(json.dumps({"ok": False, "phase": "validate", + "reason": "--session-id is required for " + "--to opencode (the transfer " + "names the holding session)"})) + return 2 + binds = {} + for b in args.bind: + try: + t, s = b.split(":", 1) + binds[int(t)] = s + except ValueError: + print(json.dumps({"ok": False, "phase": "validate", + "reason": f"bad --bind {b!r} " + f"(want TASK:SESSION)"})) + return 2 + records, ok = dispatch( + args.queue, args.count, args.target, args.worker, args.lane, + args.reason, args.notes, args.session_id, binds, + args.release_failures, args.lease_seconds, + dry_run=args.dry_run) + for rec in records: + print(json.dumps(rec)) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/pm-stack/opencode-claimant/test_dispatch_batch.py b/pm-stack/opencode-claimant/test_dispatch_batch.py new file mode 100644 index 0000000000..f8867c380e --- /dev/null +++ b/pm-stack/opencode-claimant/test_dispatch_batch.py @@ -0,0 +1,300 @@ +#!/usr/bin/env python3 +"""Tests for dispatch_batch.py (#8217). + +The batch claim + per-item dispatch driver: one batch claim, then +every item handed to a DEDICATED sub-task session in the same +touch (opencode via send_to_opencode.send, Muse via a lane-spawned +sub-session bound by id), every bind verified from live queue +state, and any failed item never left claimed-idle (released back +to queued with --release-failures, else held by the lane direct). + +Effects are faked at dispatch_batch's own seams (queue, run_send, +worktree_for, bound_session_id), so the suite runs anywhere: + + python3 -m unittest test_dispatch_batch -v +""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import sys +import unittest +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def _load(name: str): + path = HERE / f"{name}.py" + spec = importlib.util.spec_from_file_location(f"dbt_{name}", path) + mod = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = mod + spec.loader.exec_module(mod) + return mod + + +db = _load("dispatch_batch") + +QUEUE = "repo-health-code-pilot" +WORKER = "repo-worker-code" + + +def row(task_id: int, issue: int) -> dict: + return { + "id": task_id, + "status": "claimed", + "payload": { + "repo": "developing-today/code", + "issue": {"number": issue}, + }, + } + + +class FakeQueue: + """db.queue stand-in: the claim answers scripted rows, other + verbs are recorded. Returns (rc, stdout, stderr) like the real + launch_one.queue.""" + + def __init__(self, claim_rows): + self.claim_rows = claim_rows + self.calls: list[tuple] = [] + + def __call__(self, *args, timeout=120): + self.calls.append(args) + if args[0] == "claim": + body = { + "tasks": self.claim_rows, + "claimed": len(self.claim_rows), + "requested": 5, + "guard_held": [], + } + return 0, json.dumps(body), "" + return 0, "{}", "" + + def verbs(self, verb: str) -> list[tuple]: + return [c for c in self.calls if c[0] == verb] + + +class DispatchBatchTests(unittest.TestCase): + def setUp(self): + self.worktree_calls: list[tuple] = [] + self.bound: dict[int, str | None] = {} + + def fake_worktree(primary, task_id, issue): + self.worktree_calls.append((primary, task_id, issue)) + return f"/tmp/fleet-wt/queue-{task_id}-{issue}-dispatch", True, None + + def fake_bound(queue_name, task_id): + return self.bound.get(task_id), None + + self._orig = { + "queue": db.queue, + "run_send": db.run_send, + "worktree_for": db.worktree_for, + "bound_session_id": db.bound_session_id, + } + db.worktree_for = fake_worktree + db.bound_session_id = fake_bound + + def tearDown(self): + db.queue = self._orig["queue"] + db.run_send = self._orig["run_send"] + db.worktree_for = self._orig["worktree_for"] + db.bound_session_id = self._orig["bound_session_id"] + + def run_main(self, argv, claim_rows, send_impl=None): + fake_q = FakeQueue(claim_rows) + db.queue = fake_q + if send_impl is not None: + db.run_send = send_impl + out = io.StringIO() + with contextlib.redirect_stdout(out): + rc = db.main(["dispatch_batch.py", *argv]) + records = [ + json.loads(line) + for line in out.getvalue().splitlines() + if line.startswith("{") + ] + return rc, records, fake_q + + def base_argv(self, *extra): + return [ + "--queue", QUEUE, + "--worker", WORKER, + "--count", "2", + "--reason", "batch dispatch for the test bundle", + "--notes", "lane notes for the batch", + *extra, + ] + + def items(self, records): + return [r for r in records if r.get("kind") != "dispatch_batch"] + + # -- dry run ---------------------------------------------------- + + def test_dry_run_claims_and_dispatches_nothing(self): + rows = [row(101, 555), row(102, 556)] + rc, records, fake_q = self.run_main( + self.base_argv("--to", "opencode", "--session-id", "ses_lane", + "--dry-run"), + rows, + send_impl=lambda *a: self.fail("dry run must not send"), + ) + self.assertEqual(rc, 0) + self.assertEqual(len(records), 1, "dry run prints the summary only") + summary = records[0] + self.assertTrue(summary["ok"]) + self.assertTrue(summary["dry_run"]) + self.assertEqual(summary["tasks"], [101, 102]) + claim = fake_q.verbs("claim")[0] + self.assertIn("--count", claim) + self.assertIn("openchamber", claim, "the claim declares the family") + self.assertEqual(self.worktree_calls, []) + + # -- opencode dispatch ------------------------------------------ + + def test_opencode_items_bound_to_dedicated_sessions(self): + rows = [row(101, 555), row(102, 556)] + sends = [] + + def send_impl(queue_name, task_id, worker, from_session, + reason, notes, worktree): + sends.append({ + "task": task_id, "from": from_session, + "reason": reason, "notes": notes, "worktree": worktree, + }) + sid = f"ses_item_{task_id}" + self.bound[task_id] = sid + return {"ok": True, "session_id": sid, "task": task_id} + + rc, records, _ = self.run_main( + self.base_argv("--to", "opencode", "--session-id", "ses_lane"), + rows, send_impl=send_impl) + self.assertEqual(rc, 0) + items = self.items(records) + self.assertEqual([r["outcome"] for r in items], ["bound", "bound"]) + sessions = [r["session_id"] for r in items] + self.assertEqual(len(set(sessions)), 2, "one session per item") + worktrees = [r["worktree"] for r in items] + self.assertEqual(len(set(worktrees)), 2, "one worktree per item") + for s in sends: + self.assertEqual(s["from"], "ses_lane") + self.assertEqual(s["reason"], + "batch dispatch for the test bundle") + self.assertEqual(s["notes"], "lane notes for the batch") + self.assertIn(str(s["task"]), s["worktree"]) + + def test_failed_send_releases_item_with_flag(self): + rows = [row(101, 555), row(102, 556)] + + def send_impl(queue_name, task_id, *rest): + if task_id == 102: + return {"ok": False, "phase": "create", + "reason": "session create refused"} + sid = "ses_item_101" + self.bound[task_id] = sid + return {"ok": True, "session_id": sid} + + rc, records, fake_q = self.run_main( + self.base_argv("--to", "opencode", "--session-id", "ses_lane", + "--release-failures"), + rows, send_impl=send_impl) + self.assertEqual(rc, 1) + by_task = {r["task"]: r for r in self.items(records)} + self.assertEqual(by_task[101]["outcome"], "bound") + self.assertEqual(by_task[102]["outcome"], "released_to_queue") + self.assertEqual(by_task[102]["phase"], "create") + releases = fake_q.verbs("release") + self.assertEqual(len(releases), 1) + self.assertEqual(releases[0][1], "102") + + def test_failed_send_held_by_lane_by_default(self): + rows = [row(101, 555)] + + def send_impl(queue_name, task_id, *rest): + return {"ok": False, "phase": "pool", + "reason": "opencode session pool is full"} + + rc, records, fake_q = self.run_main( + self.base_argv("--to", "opencode", "--session-id", "ses_lane", + "--count", "1"), + rows, send_impl=send_impl) + self.assertEqual(rc, 1) + item = self.items(records)[0] + self.assertEqual(item["outcome"], "held_by_lane_direct") + self.assertEqual(fake_q.verbs("release"), [], + "no release without the flag") + + def test_unverified_bind_releases_item(self): + rows = [row(101, 555)] + # The send reports a session, but live state never shows it. + def send_impl(queue_name, task_id, *rest): + return {"ok": True, "session_id": "ses_ghost"} + + rc, records, fake_q = self.run_main( + self.base_argv("--to", "opencode", "--session-id", "ses_lane", + "--count", "1", "--release-failures"), + rows, send_impl=send_impl) + self.assertEqual(rc, 1) + item = self.items(records)[0] + self.assertEqual(item["outcome"], "released_to_queue") + self.assertEqual(item["phase"], "verify") + self.assertEqual(len(fake_q.verbs("release")), 1) + + # -- Muse dispatch ---------------------------------------------- + + def test_claude_item_with_bind_is_bound(self): + rows = [row(101, 555)] + self.bound[101] = "ses_claude_1" + rc, records, fake_q = self.run_main( + self.base_argv("--to", "Muse", "--count", "1", + "--bind", "101:ses_claude_1"), + rows, + send_impl=lambda *a: self.fail("Muse items never send"), + ) + self.assertEqual(rc, 0) + item = self.items(records)[0] + self.assertEqual(item["outcome"], "bound") + self.assertEqual(item["session_id"], "ses_claude_1") + # Lane-direct assignment + dispatch checkpoint precede the bind. + self.assertEqual(len(fake_q.verbs("lane")), 1) + self.assertEqual(len(fake_q.verbs("checkpoint")), 1) + self.assertEqual(len(fake_q.verbs("bind")), 1) + + def test_claude_item_without_bind_is_prepared_unbound(self): + rows = [row(101, 555)] + rc, records, fake_q = self.run_main( + self.base_argv("--to", "Muse", "--count", "1"), + rows) + self.assertEqual(rc, 1, "an unbound Muse item fails the batch") + item = self.items(records)[0] + self.assertEqual(item["outcome"], "prepared_unbound") + self.assertIn("bind_command", item) + self.assertEqual(fake_q.verbs("bind"), []) + + # -- validation --------------------------------------------------- + + def test_count_over_cap_refused_before_claiming(self): + called = [] + db.queue = lambda *a, timeout=120: called.append(a) or (0, "{}", "") + out = io.StringIO() + with contextlib.redirect_stdout(out): + rc = db.main(["dispatch_batch.py", + *self.base_argv("--to", "opencode", + "--session-id", "ses_lane", + "--count", "6")]) + self.assertEqual(rc, 2) + self.assertEqual(called, [], "over-cap never reaches the broker") + + def test_opencode_requires_session_id(self): + rc, records, fake_q = self.run_main( + self.base_argv("--to", "opencode"), [row(101, 555)]) + self.assertEqual(rc, 2) + self.assertEqual(fake_q.calls, []) + + +if __name__ == "__main__": + unittest.main()