diff --git a/doc/fleet/queue-turso-cutover.md b/doc/fleet/queue-turso-cutover.md index 6922242fae..1fd8dbaad3 100644 --- a/doc/fleet/queue-turso-cutover.md +++ b/doc/fleet/queue-turso-cutover.md @@ -413,3 +413,34 @@ at their attempt cap. The broker now owns waiting: was the one place bookkeeping cycles consumed attempts (task 10501 reached 24/24 on handoff cycles alone). Direct claims and bound sessions mid-work still return to `queued`. + +## Amendment — the sink gets its own status (#8234, 2026-11-10) + +The section above describes the #8184 landing as built; two of +its mechanisms were superseded the same day, first by #8187 +(lanes DO collect sink rows through the default pick and flip +them direct — the `NOT (PARKED_HANDOFF_SQL)` exclusion is gone) +and then by #8234, Drew's ruling "sink gets its own status, drop +the fake timer": + +- The handoff sink is status **`handed_off`**, not `parked`. + `parked` now means only a genuine broker-owned wait + (`wait_kind` + `ready_condition` + floored `not_before`). +- The park verb classifies its own landing: a park whose merged + progress is a recorded opencode handoff with no caller-declared + genuine wait lands in `handed_off` with every wait field NULL. + A caller-attached real condition always wins — that park is a + genuine wait even on a handoff-shaped row. +- `expire_leases` returns an expired sink-shaped claim to + `handed_off` with `not_before = NULL` and NO ready_condition — + the +1200s fake timer the sink pick never read is deleted. +- Sink membership is the status, on both sides of the wire: + neither the broker's pick SQL nor the claimant's poll reads a + progress stage to decide it (the broker and poll once read + different stage sources and disagreed — #8192, folded in). +- The wake verb refuses `handed_off` rows (not a wait; already + claimable), and `fleet queue health` reports `handed_off` as + its own bucket. Existing sink-shaped `parked` rows were moved + by one auditable migration (event kind + `handoff_status_migration`); rows carrying a genuine wait + stayed `parked`. diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index b7b9ce14f2..69d75b57ba 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -1371,18 +1371,19 @@ fn cmd_claim(rest: &[String]) -> i32 { Ok(None) => {} Err(e) => die(2, &e), } - // --handoff: the no-id collection of the next parked recorded - // opencode handoff (#8097 Rule 1) — the claimant's default - // parked-handoff path. The BROKER picks the row; the caller - // names no task id. (--task remains the special-case claim.) + // --handoff: the no-id collection of the next recorded + // opencode handoff from the sink (status 'handed_off', #8234; + // #8097 Rule 1) — the claimant's default handoff path. The + // BROKER picks the row; the caller names no task id. (--task + // remains the special-case claim.) if args.has("handoff") { - body["pick"] = json!("parked_handoff"); + body["pick"] = json!("handed_off"); } // --task : by-id claim — take exactly that row when the // broker's by-id predicate allows it (a queued row under the - // ordinary predicate, or a parked recorded opencode handoff). - // The opencode claimant uses this to collect handed-off tasks - // out of the parked sink; a plain claim never names a task. + // ordinary predicate, or a sink row). The opencode claimant + // uses this to collect handed-off tasks out of the sink; a + // plain claim never names a task. if let Some(task) = args.get_i64("task") { body["task_id"] = json!(task); } diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index db0d0eaad2..ffa703f9ac 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -1015,7 +1015,7 @@ fn verb_coverage(t: &TursoBackend, req: &Value) -> Value { let rows = t.query_objs( "SELECT id, status, dedupe_key FROM tasks \ WHERE queue = ? AND dedupe_key IS NOT NULL \ - AND status IN ('queued','claimed','parked','blocked')", + AND status IN ('queued','claimed','parked','handed_off','blocked')", &[Arg::Text(queue.clone())], &[], )?; @@ -1215,15 +1215,14 @@ fn expire_leases(t: &TursoBackend) -> Result { let to_sink = expired_claim_returns_to_sink(&progress); let (progress, cleared) = clear_binding(&progress, "expire_leases"); let upd = if to_sink { - let sink_nb = after_iso(1200); + // #8234: the sink is its own status now — the return + // lands in 'handed_off' with NO wait fields at all. The + // pre-#8234 shape stamped a fresh not_before = +1200s + // and a {"kind": "time"} ready_condition here: a fake + // timer, since the sink pick never read it. t.exec( - "UPDATE tasks SET status = 'parked', worker_id = NULL, lease_until = NULL, \ - not_before = ?, park_kind = 'relative', wait_kind = NULL, \ - ready_condition = ?, progress = ?, updated_at = ? \ - WHERE id = ? AND status = 'claimed' AND lease_until < ?", + sink_return_sql(), &[ - Arg::Text(sink_nb.clone()), - Arg::Text(json!({"kind": "time", "until": sink_nb}).to_string()), Arg::Text(progress.to_string()), Arg::Text(now.clone()), Arg::Int(id), @@ -1253,7 +1252,7 @@ fn expire_leases(t: &TursoBackend) -> Result { Some(id), "lease_expired", &json!({"via": "expire_leases", "cleared_session_id": cleared, - "return": if to_sink { "handoff_sink" } else { "queued" }}), + "return": if to_sink { "handed_off" } else { "queued" }}), )?; if let Some(old) = cleared { on_binding_cleared(t, &worker, id, &old, "expire_leases")?; @@ -1351,7 +1350,7 @@ fn req_bool(req: &Value, key: &str) -> Option { /// the live row. Terminal rows (done/cancelled/failed) do NOT block /// the key (#6838): PG's enqueue revived on dedupe-over-terminal, /// and the Turso port dropped that nuance (cutover doc deviation 6). -pub const LIVE_STATUSES: [&str; 4] = ["queued", "claimed", "parked", "blocked"]; +pub const LIVE_STATUSES: [&str; 5] = ["queued", "claimed", "parked", "handed_off", "blocked"]; pub const TERMINAL_STATUSES: [&str; 3] = ["done", "cancelled", "failed"]; /// Partition the rows sharing one (queue, dedupe_key) into the live @@ -1678,7 +1677,7 @@ fn quarantine_task(t: &TursoBackend, id: i64, reason: &str) -> Result<(), TErr> /// claim path, which is where such rows would otherwise circulate. fn quarantine_payload_missing(t: &TursoBackend, queue: &str) -> Result<(), TErr> { let rows = t.query_objs( - "SELECT id FROM tasks WHERE queue = ? AND status IN ('queued', 'parked') \ + "SELECT id FROM tasks WHERE queue = ? AND status IN ('queued', 'parked', 'handed_off') \ AND (payload IS NULL OR payload = '' OR payload = '{}')", &[Arg::Text(queue.to_string())], &[], @@ -1821,19 +1820,21 @@ fn stamp_claim_model( Ok(()) } -/// The SQL predicate mirroring is_parked_handoff, for the broker's -/// no-id handoff pick (#8097 Rule 1): a parked recorded opencode -/// handoff — progress lane opencode, a yield stage (the top-level -/// stage, else the last checkpoint's), and no session binding. -/// The park verb's default not_before timer is the handoff sink's -/// bookkeeping, not a genuine wait, so the predicate deliberately -/// ignores not_before. -const PARKED_HANDOFF_SQL: &str = "status = 'parked' \ +/// The SQL predicate mirroring is_handed_off, for the broker's +/// no-id handoff pick (#8097 Rule 1): a row in the handoff sink — +/// status 'handed_off' (#8234), progress lane opencode, and no +/// session binding. Sink membership is the STATUS, written once +/// by the park verb's classification, the lease-expiry sink +/// return, or the #8234 migration; this predicate deliberately +/// does NOT reconstruct it from progress stage — the broker and +/// the claimant poll once disagreed about which stage source +/// (top-level vs last_checkpoint) named a sink row, and rows +/// stranded in that gap (#8192). The lane and session conditions +/// stay as guards: a bound row is a live session's business, and +/// only an opencode yield is the claimant's to collect. +const HANDOFF_SQL: &str = "status = 'handed_off' \ AND json_extract(progress, '$.lane') = 'opencode' \ - AND json_extract(progress, '$.session_id') IS NULL \ - AND COALESCE(json_extract(progress, '$.stage'), \ - json_extract(progress, '$.last_checkpoint.stage')) \ - IN ('handed_off', 'launch_failed')"; + AND json_extract(progress, '$.session_id') IS NULL"; /// The yield stage a task's progress records: the top-level `stage` /// when present, else the last checkpoint's stage (the checkpoint @@ -1848,24 +1849,24 @@ fn progress_stage(progress: &Value) -> Option<&str> { }) } -/// A parked row is a RECORDED OPENCODE HANDOFF when its progress -/// carries the opencode lane assignment, a yield stage -/// (handed_off, or launch_failed after a claimant recovery), and no -/// session binding. This is the state every lane handoff lands in: -/// the claiming lane checkpoints handed_off and then parks the task -/// as its handoff sink (park clears the claim and stamps a default -/// +20-minute timer), so the row sits parked — never claimed — while -/// the opencode claimant's discovery only ever read claimed rows. -/// 164 such rows sat parked in repo-health-code-pilot alone on -/// 2026-11-09 while their issues (#7907, #6533) cycled -/// claim → handoff → park → re-claim for days. A genuine wait park -/// never matches: it carries a different stage (parked, gated, -/// probe_*) or a direct lane, and a bound session's park cleared -/// the binding but keeps its working stage. /// The progress shape of a recorded opencode handoff (#8184): /// the opencode lane assignment plus a yield stage (handed_off, or /// launch_failed after a claimant recovery), regardless of the -/// row's status or session binding. +/// row's status or session binding. This shape is the WRITE-side +/// classification: the park verb uses it to decide that a park +/// lands in the sink (status 'handed_off', #8234), and +/// expire_leases uses it to decide that an expired claimed row +/// returns to the sink. It is never used to decide sink +/// MEMBERSHIP for a resting row — that is the status itself +/// (is_handed_off) — because the shape's stage can be read two +/// ways (progress_stage prefers the top-level stage; the +/// claimant's normalize_row lifts last_checkpoint), and #8192 was +/// exactly the two readers disagreeing about a resting row. +/// Historically this shape sat in status 'parked' with the park +/// verb's default +20-minute timer stamped on it; 164 such rows +/// sat in repo-health-code-pilot alone on 2026-11-09 while their +/// issues (#7907, #6533) cycled claim → handoff → park → re-claim +/// for days. fn handoff_shape(progress: &Value) -> bool { progress.get("lane").and_then(|v| v.as_str()) == Some("opencode") && matches!( @@ -1874,38 +1875,84 @@ fn handoff_shape(progress: &Value) -> bool { ) } -fn is_parked_handoff(row: &Value) -> bool { - if row.get("status").and_then(|v| v.as_str()) != Some("parked") { +/// A row is IN the handoff sink (#8234) when its status is +/// 'handed_off', its progress carries the opencode lane, and no +/// session is bound. The status is the membership — written only +/// by the park classification, the lease-expiry sink return, and +/// the #8234 migration, all of which gate on handoff_shape plus +/// an absent binding — so the lane check here is a guard, not a +/// reconstruction, and no stage is consulted at all (#8192). +fn is_handed_off(row: &Value) -> bool { + if row.get("status").and_then(|v| v.as_str()) != Some("handed_off") { return false; } let progress = row.get("progress").cloned().unwrap_or(json!({})); + if progress.get("lane").and_then(|v| v.as_str()) != Some("opencode") { + return false; + } + match progress.get("session_id") { + Some(Value::Null) | None => true, + Some(_) => false, + } +} + +/// Whether a park lands in the handoff sink (#8234): the merged +/// progress is a recorded opencode handoff (handoff_shape), and +/// the caller declared no genuine wait — the ready condition is +/// absent (defaulted by the park verb), or a bare {"kind": "time"} +/// timer, which on a handoff row was only ever the park verb's +/// own default bookkeeping. Any other condition kind (ci/triage +/// floors aside, task_terminal, task_status, event_seen, +/// quota_reset, person_answer) is a real wait the caller named, +/// and that park stays a park. The caller passes the +/// binding-cleared merged progress, so a bound session's row — +/// whose stage may still read as a yield — never sinks. +fn handoff_park(progress: &Value, condition_defaulted: bool, condition: &Value) -> bool { + if !handoff_shape(progress) { + return false; + } match progress.get("session_id") { Some(Value::Null) | None => {} Some(_) => return false, } - handoff_shape(&progress) + condition_defaulted || condition.get("kind").and_then(|v| v.as_str()) == Some("time") } /// Where an expired claim returns (#8184): a claimed row whose -/// progress is a recorded opencode handoff goes back to the parked -/// handoff sink, never to queued — the claimant collects it from -/// parked at +0 attempts, so a claimant launch that died on the -/// lease can never burn an attempt through the queued interlude. -/// Anything else (a direct claim, a bound session mid-work whose -/// stage advanced past the yield stages) returns to queued as -/// before. +/// progress is a recorded opencode handoff goes back to the +/// handoff sink (status 'handed_off', #8234), never to queued — +/// the claimant collects it from the sink at +0 attempts, so a +/// claimant launch that died on the lease can never burn an +/// attempt through the queued interlude. Anything else (a direct +/// claim, a bound session mid-work whose stage advanced past the +/// yield stages) returns to queued as before. fn expired_claim_returns_to_sink(progress: &Value) -> bool { handoff_shape(progress) } +/// The lease-expiry sink return as a statement builder (#8234), +/// extracted so the regression tests pin its shape without a +/// live store (the claim_update_sql pattern): an expired claimed +/// handoff lands in status 'handed_off' with every wait field +/// NULL — no not_before, no park_kind, no ready_condition. The +/// pre-#8234 return stamped a fresh +1200s not_before and a +/// {"kind": "time"} ready_condition: a fake timer on a state +/// that is not a wait, which the sink pick never read. +fn sink_return_sql() -> &'static str { + "UPDATE tasks SET status = 'handed_off', worker_id = NULL, lease_until = NULL, \ + not_before = NULL, park_kind = NULL, wait_kind = NULL, \ + ready_condition = NULL, progress = ?, updated_at = ? \ + WHERE id = ? AND status = 'claimed' AND lease_until < ?" +} + /// Whether a by-id claim (claim_repo_task with task_id) may take /// exactly this row. Two shapes only: a queued row under the pick /// path's ordinary predicate (attempts cap + not_before), or a -/// parked recorded handoff (is_parked_handoff) — the handoff park's -/// not_before is the park verb's default timer, not a real wait, -/// so it does not gate the claimant collecting its own handoff. -/// Anything else (claimed, blocked, a genuine wait park, a queued -/// row parked into the future) is not claimable by id. +/// sink row (is_handed_off, #8234) — the sink is not a wait, so +/// nothing gates the claimant collecting its own handoff. +/// Anything else (claimed, blocked, a genuine wait park — a +/// 'parked' row is never a sink row since #8234, whatever its +/// progress carries) is not claimable by id. fn by_id_claimable(row: &Value, now: &str) -> bool { // #8187: platform is a mark, not a filter — a by-id claim takes // the row whatever platform either side carries (or none). @@ -1919,7 +1966,7 @@ fn by_id_claimable(row: &Value, now: &str) -> bool { let nb = row.get("not_before").and_then(|v| v.as_str()); attempts < max && nb.map_or(true, |nb| nb <= now) } - Some("parked") => is_parked_handoff(row), + Some("handed_off") => is_handed_off(row), _ => false, } } @@ -2185,7 +2232,7 @@ fn claim_by_id( let upd = t.exec( "UPDATE tasks SET status = 'claimed', worker_id = ?, claimed_at = ?, \ lease_until = ?, \ - attempts = attempts + (CASE WHEN status = 'parked' THEN 0 ELSE 1 END), \ + attempts = attempts + (CASE WHEN status IN ('parked', 'handed_off') THEN 0 ELSE 1 END), \ lane_id = ?, platform = COALESCE(?, platform), \ park_kind = NULL, wait_kind = NULL, not_before = NULL, \ updated_at = ? \ @@ -2293,7 +2340,7 @@ fn claim_update_sql(pick_predicate: &str) -> String { format!( "UPDATE tasks SET status = 'claimed', worker_id = ?, claimed_at = ?, \ lease_until = ?, \ - attempts = attempts + (CASE WHEN status = 'parked' THEN 0 ELSE 1 END), \ + attempts = attempts + (CASE WHEN status IN ('parked', 'handed_off') THEN 0 ELSE 1 END), \ lane_id = ?, platform = COALESCE(?, platform), \ park_kind = NULL, wait_kind = NULL, not_before = NULL, \ updated_at = ? \ @@ -2302,30 +2349,30 @@ fn claim_update_sql(pick_predicate: &str) -> String { ) } -/// The default (lane) pick predicate (#8184, amended #8187): -/// queued rows due under the attempts cap, or parked rows whose -/// wait timer has passed — plus, as a third branch, parked recorded -/// opencode handoffs (the #8185 handoff sink) WITHOUT the not_before -/// gate. #8184 excluded sink rows from lanes entirely (they were +/// The default (lane) pick predicate (#8184, amended #8187, +/// #8234): queued rows due under the attempts cap, or parked rows +/// whose wait timer has passed — plus, as a third branch, handoff +/// sink rows (status 'handed_off', the #8185 sink with its own +/// status since #8234) with no timer at all: the sink is not a +/// wait. #8184 excluded sink rows from lanes entirely (they were /// claimant-owned, and serving one to a lane only re-ran the /// claim -> handoff -> park cycle); #8187 reverses that: a lane is -/// single-session by default, claims a sink row as an ordinary -/// parked claim (+0 attempts, per the claim UPDATE's parked CASE), -/// and verb_lane flips its ledger assignment to direct when the -/// lane passes --exclusion-reason (see lane_reassignment_flip). -/// The claimant's parked_handoff pick and by-id claim keep working -/// unchanged. The timed parked branch keeps its NOT sink exclusion -/// so a sink row is admitted by exactly one branch, and genuine -/// wait parks keep releasing through claim at not_before. The sink -/// branch carries no `?` placeholder, so the pick SELECT and the -/// claim UPDATE re-check keep their two `now` arguments. +/// single-session by default, claims a sink row at +0 attempts +/// (per the claim UPDATE's parked/handed_off CASE), and verb_lane +/// flips its ledger assignment to direct when the lane passes +/// --exclusion-reason (see lane_reassignment_flip). The claimant's +/// handoff pick and by-id claim keep working unchanged. Since +/// #8234 a sink row is never 'parked', so the timed parked branch +/// needs no sink exclusion — genuine wait parks release through +/// claim at not_before, and only there. The sink branch carries +/// no `?` placeholder, so the pick SELECT and the claim UPDATE +/// re-check keep their two `now` arguments. fn default_pick_predicate() -> String { format!( "(status = 'queued' AND attempts < max_attempts \ AND (not_before IS NULL OR not_before <= ?)) \ - OR (status = 'parked' AND not_before IS NOT NULL AND not_before <= ? \ - AND NOT ({PARKED_HANDOFF_SQL})) \ - OR ({PARKED_HANDOFF_SQL})" + OR (status = 'parked' AND not_before IS NOT NULL AND not_before <= ?) \ + OR ({HANDOFF_SQL})" ) } @@ -2644,13 +2691,14 @@ fn claim_pick_once( // #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 + // (queued rows due; parked rows whose timer has passed; + // sink rows by their own branch). + // Handoff mode picks the next sink row (HANDOFF_SQL: + // status 'handed_off', #8234) with no caller-named id + // and no timer gating — Rule 1's default collection // path for the claimant. let pick_predicate = if handoff_pick { - PARKED_HANDOFF_SQL.to_string() + HANDOFF_SQL.to_string() } else { default_pick_predicate() }; @@ -2761,7 +2809,7 @@ fn claim_pick_once( "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" }, + "pick": if handoff_pick { "handed_off" } else { "default" }, }), &row, ), @@ -2871,13 +2919,16 @@ fn verb_claim(t: &TursoBackend, req: &Value) -> Value { Err(e) => return fail(2, format!("claim_repo_task: {e}")), }; // #8097 Rule 1: pick mode. The default pick is the queue's next - // suitable item. "parked_handoff" restricts the pick to parked - // recorded opencode handoffs — the broker chooses the row, the - // caller names NO task id. Naming a task (task_id, below) stays - // the explicit special case. + // suitable item. "handed_off" restricts the pick to recorded + // opencode handoffs in the sink (status 'handed_off', #8234) — + // the broker chooses the row, the caller names NO task id. + // Naming a task (task_id, below) stays the explicit special + // case. ("parked_handoff" is the pre-#8234 spelling of the + // mode, kept as a deprecated alias so a straggler caller fails + // soft; the sink has not been a park since #8234.) let handoff_pick = match req_str(req, "pick") { None => false, - Some("parked_handoff") => true, + Some("handed_off") | Some("parked_handoff") => true, Some(other) => { return fail(2, format!("claim_repo_task: unknown pick mode {other:?}")); } @@ -2919,9 +2970,9 @@ fn verb_claim(t: &TursoBackend, req: &Value) -> Value { // 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 - // specific row (e.g. a single parked handoff); the default - // flow never names a task — the claimant collects parked - // handoffs through the pick="parked_handoff" mode above. + // specific row (e.g. a single sink row); the default flow + // never names a task — the claimant collects sink rows + // through the pick="handed_off" mode above. if let Some(want_id) = req_i64(req, "task_id") { // #8210: task_id + from_session is a session-to-session // TRANSFER — take the row directly from its current @@ -3528,41 +3579,73 @@ fn verb_park(t: &TursoBackend, req: &Value) -> Value { &row.get("result").cloned().unwrap_or(json!({})), &json!({"park_reason": reason}), ); + // #8234: the park verb classifies its own landing. A park whose + // merged progress is a recorded opencode handoff with no + // caller-declared genuine wait is not a wait at all: it lands + // in the handoff sink (status 'handed_off', every wait field + // NULL) instead of 'parked' under the default timer. The + // triage classification above is a genuine wait by #8184's own + // rule and never sinks. + let to_sink = wk != "triage" && handoff_park(&progress, condition_defaulted, &condition); let work = (|| -> Result { - t.exec( - "UPDATE tasks SET status = 'parked', worker_id = NULL, lease_until = NULL, \ - not_before = ?, park_kind = ?, wait_kind = ?, ready_condition = ?, \ - last_checked_at = ?, check_outcome = NULL, progress = ?, result = ?, \ - updated_at = ? WHERE id = ?", - &[ - Arg::Text(not_before.clone()), - Arg::Text(park_kind.to_string()), - Arg::Text(wk.to_string()), - Arg::Text(condition.to_string()), - Arg::Text(now_iso()), - Arg::Text(progress.to_string()), - Arg::Text(result.to_string()), - Arg::Text(now_iso()), - Arg::Int(task_id), - ], - )?; + if to_sink { + t.exec( + "UPDATE tasks SET status = 'handed_off', worker_id = NULL, lease_until = NULL, \ + not_before = NULL, park_kind = NULL, wait_kind = NULL, ready_condition = NULL, \ + last_checked_at = ?, check_outcome = NULL, progress = ?, result = ?, \ + updated_at = ? WHERE id = ?", + &[ + Arg::Text(now_iso()), + Arg::Text(progress.to_string()), + Arg::Text(result.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + } else { + t.exec( + "UPDATE tasks SET status = 'parked', worker_id = NULL, lease_until = NULL, \ + not_before = ?, park_kind = ?, wait_kind = ?, ready_condition = ?, \ + last_checked_at = ?, check_outcome = NULL, progress = ?, result = ?, \ + updated_at = ? WHERE id = ?", + &[ + Arg::Text(not_before.clone()), + Arg::Text(park_kind.to_string()), + Arg::Text(wk.to_string()), + Arg::Text(condition.to_string()), + Arg::Text(now_iso()), + Arg::Text(progress.to_string()), + Arg::Text(result.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + } t.exec("DELETE FROM leases WHERE task_id = ?", &[Arg::Int(task_id)])?; if let Some(old) = &cleared { on_binding_cleared(t, &worker, task_id, old, "park_task")?; } + let detail = if to_sink { + json!({ + "reason": reason, "status": "handed_off", + "park_kind": Value::Null, "wait_kind": Value::Null, + "not_before": Value::Null, "ready_condition": Value::Null, + "cleared_session_id": cleared, + }) + } else { + json!({ + "reason": reason, "status": "parked", + "park_kind": park_kind, "wait_kind": wk, + "not_before": not_before, "ready_condition": condition, + "cleared_session_id": cleared, + }) + }; event( t, Some(&worker), Some(task_id), "parked", - &with_marks( - &json!({ - "reason": reason, "park_kind": park_kind, "wait_kind": wk, - "not_before": not_before, "ready_condition": condition, - "cleared_session_id": cleared, - }), - &row, - ), + &with_marks(&detail, &row), )?; let row = get_task(t, task_id).map(|r| r.unwrap_or(Value::Null))?; verb_with_execution(t, req, row) @@ -3579,6 +3662,14 @@ fn verb_park(t: &TursoBackend, req: &Value) -> Value { fn wake_eligible(status: &str) -> Result<(), String> { match status { "parked" => Ok(()), + // #8234: a sink row is not a wait and cannot be woken — + // it is already claimable; the refusal says so instead of + // the generic not-a-wait message. + "handed_off" => Err( + "task status handed_off cannot be woken: a handed_off row is not \ + a wait — it is already claimable, claim it instead" + .to_string(), + ), other => Err(format!( "task status {other} cannot be woken (only parked waits)" )), @@ -4243,7 +4334,7 @@ fn verb_list(t: &TursoBackend, req: &Value) -> Value { fn health_entry(queue: &str) -> Value { json!({ "queue": queue, "queued": 0, "at_cap_queued": 0, "claimed": 0, - "parked": 0, "blocked": 0, "done": 0, "cancelled": 0, + "parked": 0, "handed_off": 0, "blocked": 0, "done": 0, "cancelled": 0, "failed": 0, "total": 0, "oldest_queued_at": Value::Null, "terminal_events_24h": 0, "terminal_events_7d": 0, }) @@ -4707,30 +4798,38 @@ mod tests { #[test] fn default_pick_drains_parked_handoff_sink_8187() { - // #8187 (amending #8184): the lane pick now ADMITS parked - // recorded opencode handoffs (the handoff sink) through a - // third branch with NO not_before gate, so lanes can claim - // stranded sink tasks and work them direct. The timed parked - // branch keeps its NOT sink exclusion (a sink row is admitted - // by exactly one branch), the queued branch keeps its - // attempts cap, and the sink branch adds no placeholder: the - // predicate still carries exactly the two `now` arguments - // the pick SELECT and claim UPDATE bind. + // #8187 (amending #8184): the lane pick ADMITS recorded + // opencode handoffs (the handoff sink) through a third + // branch with NO not_before gate, so lanes can claim + // stranded sink tasks and work them direct. #8234: the sink + // is its own status ('handed_off'), so the timed parked + // branch no longer needs its NOT sink exclusion — a sink + // row cannot be 'parked' — and the sink branch keys on the + // status, never on a reconstructed stage (#8192). The + // queued branch keeps its attempts cap, and the sink branch + // adds no placeholder: the predicate still carries exactly + // the two `now` arguments the pick SELECT and claim UPDATE + // bind. let pred = default_pick_predicate(); assert!(pred.contains("status = 'queued' AND attempts < max_attempts")); assert!(pred.contains("status = 'parked' AND not_before IS NOT NULL AND not_before <= ?")); - assert!(pred.contains("NOT (")); + assert!(!pred.contains("NOT ("), "no sink exclusion since #8234: {pred}"); + assert!(pred.contains("status = 'handed_off'")); assert!(pred.contains("json_extract(progress, '$.lane') = 'opencode'")); - assert!(pred.contains("'handed_off', 'launch_failed'")); + assert!( + !pred.contains("last_checkpoint"), + "no stage reconstruction in the pick (#8192): {pred}" + ); // Third branch: the full sink predicate, ungated. - let sink_branch = format!("OR ({PARKED_HANDOFF_SQL})"); + let sink_branch = format!("OR ({HANDOFF_SQL})"); assert!(pred.contains(&sink_branch), "sink branch present: {pred}"); assert_eq!(pred.matches("not_before <= ?").count(), 2); assert_eq!(pred.matches('?').count(), 2, "no new placeholders: {pred}"); - // And the claim UPDATE re-check carries the same sink branch. + // And the claim UPDATE re-check carries the same sink branch, + // and collecting a sink row costs no attempt (#8234). let upd = claim_update_sql(&pred); assert!(upd.contains(&sink_branch)); - assert!(upd.contains("NOT (")); + assert!(upd.contains("status IN ('parked', 'handed_off')")); assert_eq!(upd.matches("not_before <= ?").count(), 2); } @@ -5050,6 +5149,10 @@ mod tests { assert!(wake_eligible("queued").is_err()); assert!(wake_eligible("claimed").is_err()); assert!(wake_eligible("done").is_err()); + // #8234: a sink row is refused wake with the reason — it is + // not a wait at all, it is already claimable. + let err = wake_eligible("handed_off").unwrap_err(); + assert!(err.contains("already claimable"), "{err}"); } #[test] @@ -5205,6 +5308,9 @@ mod tests { let e = health_entry("repo-health-code-pilot"); assert_eq!(e.get("at_cap_queued"), Some(&json!(0))); assert_eq!(e.get("queued"), Some(&json!(0))); + // #8234: the sink is its own health bucket — 'parked' in + // health output means genuine waits only. + assert_eq!(e.get("handed_off"), Some(&json!(0))); } #[test] @@ -5388,28 +5494,44 @@ mod tests { #[test] fn by_id_claim_takes_a_parked_recorded_handoff() { - // The #7907/#6533 loop shape: opencode lane assigned, yield - // recorded under last_checkpoint (the #7706 lift), no session - // bound, parked under the park verb's default future timer. - // The future not_before must NOT gate a by-id claim — it is - // the park default, not a wait the task asked for. + // The #7907/#6533 loop shape, post-#8234: opencode lane + // assigned, yield recorded under last_checkpoint (the #7706 + // lift), no session bound — and the row RESTS IN THE SINK: + // status 'handed_off', no wait fields. The not_before on + // this fixture row is deliberately in the far future: a + // sink row's claim ignores timers entirely, because the + // sink is not a wait. let row = handoff_row( - "parked", + "handed_off", json!({ "lane": "opencode", "last_checkpoint": {"stage": "handed_off", "at": "2026-11-09T23:15:55Z"}, "session_id": null, }), ); - assert!(is_parked_handoff(&row)); + assert!(is_handed_off(&row)); assert!(by_id_claimable(&row, "2026-11-09T23:20:00Z")); - // Top-level stage and the launch_failed recovery yield are - // the same recorded handoff in their other spellings. + // The launch_failed recovery yield in the sink is the same + // recorded handoff in its other spelling. let row2 = handoff_row( - "parked", + "handed_off", json!({"lane": "opencode", "stage": "launch_failed"}), ); assert!(by_id_claimable(&row2, "2026-11-09T23:20:00Z")); + // #8192 regression: the stage sources DISAGREE on this row + // (top-level 'working' vs last_checkpoint 'handed_off') — + // sink membership is the status, so it is claimable either + // way; neither the broker nor the claimant reads a stage + // for a resting sink row anymore. + let row3 = handoff_row( + "handed_off", + json!({ + "lane": "opencode", "stage": "working", + "last_checkpoint": {"stage": "handed_off"}, + }), + ); + assert!(is_handed_off(&row3)); + assert!(by_id_claimable(&row3, "2026-11-09T23:20:00Z")); } #[test] @@ -5421,13 +5543,31 @@ mod tests { json!({"lane": "opencode", "stage": "parked", "gate": "#3801 OPEN"}), ); assert!(!by_id_claimable(&gated, "2026-11-09T23:20:00Z")); - // A direct-lane yield is the direct lane's own business. - let direct = handoff_row("parked", json!({"lane": "direct", "stage": "handed_off"})); + // #8234: a 'parked' row with handoff-SHAPED progress (the + // pre-migration / task-10995 shape: a recorded handoff that + // later took a genuine triage wait) is a genuine wait park, + // NOT a sink row — the status decides, the shape does not. + let wait_shaped = handoff_row( + "parked", + json!({ + "lane": "opencode", + "last_checkpoint": {"stage": "handed_off"}, + "session_id": null, + }), + ); + assert!(!is_handed_off(&wait_shaped)); + assert!(!by_id_claimable(&wait_shaped, "2026-11-09T23:20:00Z")); + // A direct-lane yield in the sink status is not the + // claimant's row (the lane guard holds). + let direct = handoff_row( + "handed_off", + json!({"lane": "direct", "stage": "handed_off"}), + ); assert!(!by_id_claimable(&direct, "2026-11-09T23:20:00Z")); // A bound session id means a launch already happened; the // binding is supervision's, never a fresh claim's. let bound = handoff_row( - "parked", + "handed_off", json!({ "lane": "opencode", "stage": "handed_off", "session_id": "ses_abc", @@ -5442,6 +5582,63 @@ mod tests { assert!(!by_id_claimable(&claimed, "2026-11-09T23:20:00Z")); } + #[test] + fn park_classification_lands_handoffs_in_the_sink_8234() { + // A recorded handoff parked with no declared condition + // sinks; so does one carrying only the bare time timer + // (the park verb's own default bookkeeping). + let handoff = json!({ + "lane": "opencode", + "last_checkpoint": {"stage": "handed_off"}, + "session_id": null, + }); + assert!(handoff_park(&handoff, true, &json!({"kind": "time"}))); + assert!(handoff_park(&handoff, false, &json!({"kind": "time"}))); + // A caller-named real wait always wins, even on a + // handoff-shaped row: CI, a task dependency, a quota reset. + assert!(!handoff_park(&handoff, false, &json!({"kind": "ci", "pr": 1}))); + assert!(!handoff_park( + &handoff, + false, + &json!({"kind": "task_terminal", "task_id": 7}) + )); + assert!(!handoff_park( + &handoff, + false, + &json!({"kind": "quota_reset", "at": "2026-11-13T00:00:00Z"}) + )); + // A triage-stage park is the broker's triage wait, never + // a handoff — it does not even have the handoff shape. + let triage = json!({"lane": "opencode", "stage": "awaiting_triage"}); + assert!(!handoff_park(&triage, true, &json!({"kind": "time"}))); + // A direct-lane yield is not an opencode handoff. + let direct = json!({"lane": "direct", "stage": "handed_off"}); + assert!(!handoff_park(&direct, true, &json!({"kind": "time"}))); + // A still-bound row never sinks, whatever the stage says: + // the binding means a live session owns it. + let bound = json!({ + "lane": "opencode", "stage": "handed_off", + "session_id": "ses_abc", + }); + assert!(!handoff_park(&bound, true, &json!({"kind": "time"}))); + } + + #[test] + fn sink_return_lands_in_handed_off_without_a_timer_8234() { + // The lease-expiry sink return: status 'handed_off', every + // wait field NULL, and no trace of the pre-#8234 fake timer + // (+1200s not_before with a time ready_condition). + let sql = sink_return_sql(); + assert!(sql.contains("status = 'handed_off'")); + assert!(sql.contains("not_before = NULL")); + assert!(sql.contains("ready_condition = NULL")); + assert!(sql.contains("park_kind = NULL")); + assert!(!sql.contains("1200")); + assert!(!sql.contains("'parked'")); + // Live statuses include the sink (dedupe ownership). + assert!(LIVE_STATUSES.contains(&"handed_off")); + } + #[test] fn platform_parse_accepts_only_the_two_families() { // #8097 Rule 2: unset is absence; the only set values are diff --git a/pm-stack/opencode-claimant/README.md b/pm-stack/opencode-claimant/README.md index f7c3b8a552..748d20f2ad 100644 --- a/pm-stack/opencode-claimant/README.md +++ b/pm-stack/opencode-claimant/README.md @@ -61,7 +61,7 @@ of waiting for the next claimant fire. # Read-only: is this task a launch candidate, and what would happen? python3 pm-stack/opencode-claimant/launch_one.py --preflight repo-health-code-pilot:12345 -# Live only (mode file must read `live`): collect a parked handoff's +# Live only (mode file must read `live`): collect a sink row's # claim by id if needed, create + verify + bind a session, checkpoint # launched, send the prompt, post the agent-note. Prints the bound # session_id; any failure exits non-zero and deletes a created diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index f59c9f4cca..9c52fc685b 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -481,29 +481,26 @@ def _send_prompt(session_id: str, prompt: str) -> bool: CLAIMANT_WORKER = "opencode-claimant" -def _collect_parked_handoffs(queue: str, want: int) -> Dict[int, Dict]: - """Collect up to `want` parked recorded handoffs from `queue` - WITHOUT naming a task id (#8097 Rule 1): each +def _collect_handed_offs(queue: str, want: int) -> Dict[int, Dict]: + """Collect up to `want` recorded handoffs from `queue`'s + handoff sink WITHOUT naming a task id (#8097 Rule 1): each `repo-queue claim --handoff` lets the BROKER pick the next - parked handoff (its ordinary pick order), claimed as the - claimant, so the launch flow below has a live claim to bind - against. Returns {task_id: claimed row}. - - The handing-off lane parks the task as its handoff sink, so - without collection the task is never in the claimed state the - launch flow binds against — it waited out the park timer, was - re-claimed by the next shift wave, handed off, and parked again - (#7907/#6533). Collection used to name the task - (`claim --task `); that by-id claim is now the special-case - verb (one-off revivals), and this default path does not depend - on it — the broker's handoff pick only ever returns a parked - recorded opencode handoff (unbound yield progress), never a - live claim or a genuine wait park. + sink row (its ordinary pick order), claimed as the claimant, + so the launch flow below has a live claim to bind against. + Returns {task_id: claimed row}. + + A handed-off task rests in the sink (status 'handed_off', + #8234), so without collection it is never in the claimed state + the launch flow binds against. Collection used to name the + task (`claim --task `); that by-id claim is now the + special-case verb (one-off revivals), and this default path + does not depend on it — the broker's handoff pick only ever + returns a sink row (status 'handed_off', unbound opencode + yield), never a live claim or a genuine wait park. The claim declares the claimant's family, --platform - openchamber (#8097 Rule 2): a parked handoff whose item - carries the `muse` selector is not the opencode claimant's - to collect. + openchamber (#8097 Rule 2): a sink row whose item carries the + `muse` selector is not the opencode claimant's to collect. """ collected: Dict[int, Dict] = {} for _ in range(max(want, 0)): @@ -632,20 +629,20 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: ] # Parked handoff sink (#8097 Rule 1): collect this fire's - # parked candidates' claims up front, grouped by queue, + # sink candidates' claims up front, grouped by queue, # without naming any task id — one broker-picked handoff - # claim per discovered parked candidate. A parked - # candidate whose id is not in `collected` when its turn - # comes was not collected (its pick lost a race or the - # broker had nothing claimable) and is skipped below — - # the binding is never improvised. - parked_by_queue: Dict[str, int] = {} + # claim per discovered sink candidate. A sink candidate + # whose id is not in `collected` when its turn comes was + # not collected (its pick lost a race or the broker had + # nothing claimable) and is skipped below — the binding is + # never improvised. + handed_off_by_queue: Dict[str, int] = {} for c in unbound_opencode: - if c.get("status") == "parked": - parked_by_queue[c["queue"]] = parked_by_queue.get(c["queue"], 0) + 1 + if c.get("status") == "handed_off": + handed_off_by_queue[c["queue"]] = handed_off_by_queue.get(c["queue"], 0) + 1 collected: Dict[int, Dict] = {} - for queue_name, want in parked_by_queue.items(): - collected.update(_collect_parked_handoffs(queue_name, want)) + for queue_name, want in handed_off_by_queue.items(): + collected.update(_collect_handed_offs(queue_name, want)) for candidate in unbound_opencode: if cap_room <= 0: @@ -660,18 +657,19 @@ def launch_step(mode: str, cap_room: int) -> List[Dict]: issue = candidate.get("issue", "") packet = candidate.get("packet", {}) - # Parked handoff sink: the candidate was handed off and - # then parked by its claiming lane, so no live claim - # existed to bind against until the collection above - # claimed it (as the claimant; the launched session - # then works under the claimant's worker identity). A - # candidate the collection did not claim is skipped — - # the binding is never improvised. - if candidate.get("status") == "parked": + # Handoff sink: the candidate was handed off by its + # claiming lane and rests in the sink (status + # 'handed_off'), so no live claim existed to bind + # against until the collection above claimed it (as + # the claimant; the launched session then works under + # the claimant's worker identity). A candidate the + # collection did not claim is skipped — the binding + # is never improvised. + if candidate.get("status") == "handed_off": if task_id not in collected: skips.append({ "task_id": task_id, - "reason": "parked_claim_failed" + "reason": "sink_claim_failed" }) continue candidate["status"] = "claimed" diff --git a/pm-stack/opencode-claimant/launch_one.py b/pm-stack/opencode-claimant/launch_one.py index e30ebf6b3a..936a6594ad 100644 --- a/pm-stack/opencode-claimant/launch_one.py +++ b/pm-stack/opencode-claimant/launch_one.py @@ -5,7 +5,7 @@ OpenChamber cron every few minutes: it discovers every candidate and launches under the fleet cap. It has no per-task trigger, so a handoff that should launch *now* ("handoff = immediate launch", #8187) waits -for the next fire — and a parked handoff sink can loop unlaunched. +for the next fire — and a handoff sink can loop unlaunched. This tool performs exactly the claimant's launch sequence (prompt.md step 4) for ONE named task: @@ -13,9 +13,9 @@ python3 -I launch_one.py --launch : --preflight is read-only and always allowed: it reports whether the -task is a launch candidate (claimed, or a parked recorded handoff — -progress.lane == "opencode", no session_id, stage handed_off / -launch_failed), what blocks it if anything (attempts exhausted, held +task is a launch candidate (claimed with a recorded yield, or a +sink row — status "handed_off" (#8234), progress.lane == +"opencode", no session_id), what blocks it if anything (attempts exhausted, held labels, cap saturated, mode not live), and the exact steps a launch would take. It mutates nothing: no claim, no session, no journal. @@ -24,21 +24,22 @@ reads "live": 1. re-verify the candidate through poll.py's classifiers - (is_candidate for claimed rows, is_handoff_parked for parked + (is_candidate for claimed rows, is_handoff_waiting for sink rows — the query logic lives in poll.py, not here); 2. fail closed on exhausted attempts and on held labels (held / user/owned / do-not-merge / do-not-auto-edit, read live through `gh`; an unreadable label set is a refusal, not a pass); 3. check the concurrency cap through claimant.py's cap_step (unknown cap room launches nothing); - 4. a PARKED handoff has no live claim to bind against, so collect - its claim first with the broker's by-id special-case verb + 4. a sink row (status "handed_off") has no live claim to bind + against, so collect its claim first with the broker's by-id + special-case verb (`repo-queue claim --task --worker opencode-claimant --platform openchamber`; prompt.md reserves the by-id claim for one-off revivals, which is exactly what a named per-task launch is — the claimant's default no-id `--handoff` collection cannot promise the broker picks THIS task). The session then works - under --worker opencode-claimant, as in claimant.py's parked + under --worker opencode-claimant, as in claimant.py's sink path; 5. create the worker session on the OpenCode server through claimant.py's verified transport, journal its id to @@ -70,7 +71,7 @@ This file supersedes the state-dir helper of the same name (~/.local/state/opencode-claimant/launch_one.py), which broke when poll.fetch_claimed was replaced by fetch_claimed_rows / -fetch_parked_rows and its REPO_QUEUE path went stale. +fetch_handed_off_rows and its REPO_QUEUE path went stale. """ import importlib.util @@ -145,9 +146,12 @@ def queue(*args, timeout=120): # --- Candidate discovery (delegated to poll.py) --------------------- def explain_not_candidate(row): - """Why poll.is_candidate / is_handoff_parked said no, in words a + """Why poll.is_candidate / is_handoff_waiting said no, in words a coordinator can act on. Mirrors the classifiers' checks; the - classifiers themselves stay the verdict.""" + classifiers themselves stay the verdict. (The stage line speaks + to the CLAIMED-row classifier — sink rows are not stage-gated + since #8234/#8192 — but it is harmless context for a sink row + too: the classifiers, not this text, decide.)""" prog = row.get("progress") or {} reasons = [] if prog.get("lane") != "opencode": @@ -161,7 +165,7 @@ def explain_not_candidate(row): lane_id = row.get("lane_id") if lane_id and poll.UUID_LANE.match(str(lane_id)): reasons.append(f"claiming lane {lane_id} is an OpenChamber scheduled lane") - if row.get("status") not in (None, "claimed", "parked"): + if row.get("status") not in (None, "claimed", "handed_off"): reasons.append(f"status is {row.get('status')!r}") return reasons or ["not a candidate"] @@ -169,18 +173,18 @@ def explain_not_candidate(row): def find_row(queue_name, task_id): """(row, status, candidate, reasons) for one task, read through poll.py's broker fetch helpers: claimed rows first, then the - parked handoff sink. (None, None, False, [...]) when the task is - in neither set for this queue.""" + handoff sink (status 'handed_off'). (None, None, False, [...]) + when the task is in neither set for this queue.""" for row in poll.fetch_claimed_rows(queue_name): if row.get("id") == task_id: if poll.is_candidate(row): return row, "claimed", True, [] return row, "claimed", False, explain_not_candidate(row) - for row in poll.fetch_parked_rows(queue_name): + for row in poll.fetch_handed_off_rows(queue_name): if row.get("id") == task_id: - if poll.is_handoff_parked(row): - return row, "parked", True, [] - return row, "parked", False, explain_not_candidate(row) + if poll.is_handoff_waiting(row): + return row, "handed_off", True, [] + return row, "handed_off", False, explain_not_candidate(row) return None, None, False, [f"task {task_id} not found in queue {queue_name}"] @@ -359,12 +363,12 @@ def post_agent_note(row, ref, repo, sid): # --- The launch sequence ---------------------------------------------- -def collect_parked_claim(queue_name, task_id): - """Claim THIS parked handoff by id, as the claimant. Returns - (claimed_row, None) or (None, error). The claim output is the - claimed row itself, a {"task": row} wrapper, or {"task": null} - when the broker would not hand it over; only a row whose id is - the requested task counts.""" +def collect_sink_claim(queue_name, task_id): + """Claim THIS sink row (status 'handed_off') by id, as the + claimant. Returns (claimed_row, None) or (None, error). The + claim output is the claimed row itself, a {"task": row} + wrapper, or {"task": null} when the broker would not hand it + over; only a row whose id is the requested task counts.""" try: rc, out, err = queue("claim", "--queue", queue_name, "--worker", CLAIMANT_WORKER, @@ -417,16 +421,17 @@ def launch(queue_name, task_id): "reason": "cap_saturated", "cap_room": cap_room} worker_id = row.get("worker_id") - if status == "parked": + if status == "handed_off": # No live claim exists to bind/checkpoint against: collect # this task's claim first. The successful by-id claim is the - # broker's own verification that the row is a parked recorded - # opencode handoff; the session then works as the claimant, - # exactly as in claimant.py's parked path. - claimed, claim_err = collect_parked_claim(queue_name, task_id) + # broker's own verification that the row is a sink row + # (status 'handed_off', recorded opencode handoff); the + # session then works as the claimant, exactly as in + # claimant.py's sink path. + claimed, claim_err = collect_sink_claim(queue_name, task_id) if claimed is None: return {"task": task_id, "queue": queue_name, "ok": False, - "reason": "parked_claim_failed", "detail": claim_err} + "reason": "sink_claim_failed", "detail": claim_err} worker_id = CLAIMANT_WORKER else: # Re-verify immediately before creating anything (claimant @@ -539,9 +544,9 @@ def would_steps(queue_name, row, status, worker_id): directory = REPOS[queue_name][1] prov, mdl = route_for(row) steps = [] - if status == "parked": + if status == "handed_off": steps.append( - f"collect the parked handoff's claim by id: repo-queue claim " + f"collect the sink row's claim by id: repo-queue claim " f"--queue {queue_name} --worker {CLAIMANT_WORKER} " f"--platform openchamber --task {row.get('id')}") steps += [ @@ -583,7 +588,7 @@ def preflight(queue_name, task_id): if mode != "live": blockers.append(f"mode_not_live: mode file reads {mode!r}; --launch would refuse") worker_id = row.get("worker_id") or ( - CLAIMANT_WORKER if status == "parked" else None) + CLAIMANT_WORKER if status == "handed_off" else None) return { "task": task_id, "queue": queue_name, "candidate": candidate, "ok": candidate and not blockers, diff --git a/pm-stack/opencode-claimant/poll.py b/pm-stack/opencode-claimant/poll.py index 625f3eef01..0398f27b3f 100755 --- a/pm-stack/opencode-claimant/poll.py +++ b/pm-stack/opencode-claimant/poll.py @@ -13,11 +13,10 @@ # "opencode", stage # handed_off/launch_failed, # no session_id; status - # "claimed", or "parked" - # for a handed-off task - # the handing-off lane - # parked as its sink - # (is_handoff_parked) + # "claimed", or "handed_off" + # for a task resting in + # the handoff sink (#8234; + # is_handoff_waiting) "stuck_bound": [ {id, queue, ..., session_id, session_updated} ... ], # bound tasks whose session # looks never-prompted and @@ -374,26 +373,41 @@ def fetch_claimed_rows(queue): return _fetch_rows(queue, "claimed") -def fetch_parked_rows(queue): - """Parked rows for one queue (handoff-sink candidates).""" - return _fetch_rows(queue, "parked") - - -def is_handoff_parked(row): - """A parked row is a claimant candidate iff it is a recorded - opencode handoff that was parked as the handing-off lane's sink: - the same yield contract as a claimed candidate (is_candidate — - lane opencode, recorded handed_off/launch_failed yield, no - session bound, non-UUID claiming lane), read off a parked row. - The lane's park is not a wait: verb_park stamps the default - +20-minute timer and clears the claim, so a handed-off task sits - parked, invisible to claimed-only discovery, until a later shift - wave re-claims it and parks it again (#7907/#6533 looped for - days this way). A genuine wait park never satisfies the yield - contract: its stage is the park/gate itself, not a handoff.""" - if row.get("status") not in (None, "parked"): +def fetch_handed_off_rows(queue): + """Handed_off rows for one queue (handoff-sink candidates).""" + return _fetch_rows(queue, "handed_off") + + +def is_handoff_waiting(row): + """A handed_off (sink) row is a claimant candidate iff it is a + recorded opencode handoff resting in the handoff sink: status + 'handed_off' (#8234), lane opencode, no session bound, and the + claiming lane is not itself an OpenChamber scheduled lane (the + same double-execution guard as is_candidate). + + Deliberately NO stage test. Sink membership is the STATUS — + written once by the broker's park classification, the + lease-expiry sink return, or the #8234 migration — so this + reader must not reconstruct it from a stage, and in particular + must not care whether progress.stage or + progress.last_checkpoint.stage carries the yield: the broker + and this poll once read different sources and disagreed about + a resting row (#8192). For CLAIMED rows the stage test in + is_candidate stays — there it is the launch-safety contract + (a lane mid-work must never be launched into); a sink row has + no lane working it by construction. Historically the sink sat + in status 'parked' under the park verb's default timer, and + tasks looped claim -> handoff -> park -> re-claim for days + (#7907/#6533).""" + if row.get("status") not in (None, "handed_off"): return False - return is_candidate(row) + prog = row.get("progress") or {} + if prog.get("lane") != "opencode" or prog.get("session_id"): + return False + lane_id = row.get("lane_id") + if lane_id and UUID_LANE.match(lane_id): + return False + return True def normalize_row(row): @@ -485,9 +499,9 @@ def get_candidates(rows): return [r for r in rows if is_candidate(r)] -def get_parked_candidates(rows): - """Unbound opencode-lane candidates from parked handoff rows.""" - return [r for r in rows if is_handoff_parked(r)] +def get_handed_off_candidates(rows): + """Unbound opencode-lane candidates from handoff-sink rows.""" + return [r for r in rows if is_handoff_waiting(r)] def get_stuck_bound(rows, session_by_id, active_ids, now_ms): @@ -532,9 +546,9 @@ def main(): for q in QUEUES: rows = fetch_claimed_rows(q) cands = [_candidate_entry(r, q) for r in get_candidates(rows)] - parked_rows = fetch_parked_rows(q) + handed_off_rows = fetch_handed_off_rows(q) cands.extend( - _candidate_entry(r, q) for r in get_parked_candidates(parked_rows) + _candidate_entry(r, q) for r in get_handed_off_candidates(handed_off_rows) ) stuck = [ _stuck_entry(r, q, session_by_id.get((r.get("progress") or {}).get("session_id"))) @@ -542,7 +556,7 @@ def main(): ] out["queues"][q] = { "claimed": len(rows), - "parked": len(parked_rows), + "handed_off": len(handed_off_rows), "candidates": cands, "stuck_bound": stuck, } diff --git a/pm-stack/opencode-claimant/prompt.md b/pm-stack/opencode-claimant/prompt.md index 3857db5214..e9ef5fd23a 100644 --- a/pm-stack/opencode-claimant/prompt.md +++ b/pm-stack/opencode-claimant/prompt.md @@ -84,22 +84,23 @@ outage is recoverable, a double-launch's damage is not. close — plus the live root-session count for the cap, plus a `stuck_bound` list: bound tasks whose sessions look created-but-never-prompted and dead (step 1's recovery rule, #4758). - Candidates ALSO include handed-off tasks sitting PARKED - (`status: "parked"` in the candidate entry): the handing-off lane - parks the task as its handoff sink (the park clears its claim and - stamps a default timer), so claimed-only discovery never saw them - and they looped claim → handoff → park → re-claim (#7907/#6533). - For parked candidates, claimant.py first collects their claims + Candidates ALSO include handed-off tasks resting in the + handoff sink (`status: "handed_off"` in the candidate entry, + #8234): the handing-off lane's handoff lands the task in the + sink — its own status, not a park and not a wait — so + claimed-only discovery never saw them and they once looped + claim → handoff → park → re-claim (#7907/#6533). + For sink candidates, claimant.py first collects their claims WITHOUT naming any task id (#8097 Rule 1): one - `repo-queue claim --handoff --platform openchamber` per parked + `repo-queue claim --handoff --platform openchamber` per sink candidate, as worker `opencode-claimant`, lets the BROKER pick - the next parked recorded opencode handoff (the pick only ever - returns an unbound yield, never a live claim or a genuine wait - park; the `openchamber` family declaration keeps a - `muse`-selected item out of this claimant's hands, #8097 - Rule 2). It then launches exactly as for a claimed candidate, - with the session working under `--worker opencode-claimant`. - A parked candidate the collection did not claim is skipped + the next sink row (the pick only ever returns an unbound sink + row, never a live claim or a genuine wait park; the + `openchamber` family declaration keeps a `muse`-selected item + out of this claimant's hands, #8097 Rule 2). It then launches + exactly as for a claimed candidate, with the session working + under `--worker opencode-claimant`. + A sink candidate the collection did not claim is skipped with the reason logged — never launched over a guessed claim. (The by-id claim, `claim --task `, remains only as the special-case verb for one-off revivals; no default flow uses @@ -314,7 +315,7 @@ creates the session in the task's worktree, and moves the claim with the broker's transfer claim — `repo-queue claim --task --from-session --session-id --worker opencode-claimant` — holder -> claimer in one operation, -never through queued or parked, binding the new session +never through queued, parked, or the sink, binding the new session atomically. The sender's notes ride in the launched session's prompt (SENDER NOTES section) and in `SEND_NOTES.md` in the worktree. A transferred task arrives already claimed by diff --git a/pm-stack/opencode-claimant/send_to_opencode.py b/pm-stack/opencode-claimant/send_to_opencode.py index 8fcce02667..95ff9adc0b 100644 --- a/pm-stack/opencode-claimant/send_to_opencode.py +++ b/pm-stack/opencode-claimant/send_to_opencode.py @@ -42,8 +42,8 @@ 7. the claim TRANSFER (`repo-queue claim --task --from-session --session-id --worker opencode-claimant --platform openchamber`, #8210): holder -> - claimer in one broker operation, never through queued or - parked, binding the new session atomically. The returned + claimer in one broker operation, never through queued, + parked, or the sink, binding the new session atomically. The returned row must show the claimant as worker and the new session bound; 8. checkpoint `launched` as the claimant, then the execution diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 18bfcce36c..09d133241e 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -179,10 +179,11 @@ def test_valid_candidate_launches_and_binds(self): self.assertIn("777", bind_argv) self.assertIn("ses_new1", bind_argv) - def test_parked_candidate_is_collected_without_naming_its_id(self): - # #8097 Rule 1: a parked handoff candidate is collected via - # the broker-picked handoff claim — no argv ever names the - # task id — and then launches exactly like a claimed one. + def test_sink_candidate_is_collected_without_naming_its_id(self): + # #8097 Rule 1: a sink (status 'handed_off', #8234) + # candidate is collected via the broker-picked handoff + # claim — no argv ever names the task id — and then + # launches exactly like a claimed one. binds = [] claims = [] base_fake = make_fake_run(binds) @@ -194,7 +195,7 @@ def fake_run(cmd, **kwargs): return Result(0, json.dumps({"id": 888, "status": "claimed"})) return base_fake(cmd, **kwargs) - parked = dict(CANDIDATE, id=888, status="parked", + parked = dict(CANDIDATE, id=888, status="handed_off", queue=claimant.QUEUES[0]) with patch.object(claimant, "run_poll", return_value={"candidates": [dict(parked)]}), \ @@ -211,7 +212,7 @@ def fake_run(cmd, **kwargs): self.assertNotIn("--task", claim_argv) self.assertNotIn("888", claim_argv) - def test_collect_parked_handoffs_drains_until_the_broker_has_none(self): + def test_collect_handed_offs_drains_until_the_broker_has_none(self): # The collection loop claims broker-picked handoffs until # the broker answers {"task": null}; every claim is a # no-id handoff claim under the openchamber family. @@ -225,7 +226,7 @@ def fake_run(cmd, **kwargs): return rows[len(argvs) - 1] with patch.object(claimant.subprocess, "run", fake_run): - collected = claimant._collect_parked_handoffs("q1", 5) + collected = claimant._collect_handed_offs("q1", 5) self.assertEqual(sorted(collected), [501, 502]) self.assertEqual(len(argvs), 3) for argv in argvs: diff --git a/pm-stack/opencode-claimant/test_launch_one.py b/pm-stack/opencode-claimant/test_launch_one.py index dd3303a60b..a49b68e9a4 100644 --- a/pm-stack/opencode-claimant/test_launch_one.py +++ b/pm-stack/opencode-claimant/test_launch_one.py @@ -14,11 +14,12 @@ - repo-queue resolution: ~/.local/bin/repo-queue by default (never the retired ~/fleet-brokers/bin tree), env override wins; - candidate discovery delegates to poll.py: claimed handed_off rows - and parked handoff rows are candidates; bound, unyielded, and - OpenChamber-lane rows are not, with the reason named; + and sink rows (status "handed_off", #8234) are candidates; bound, + unyielded, and OpenChamber-lane rows are not, with the reason + named; - preflight is read-only in effect: it reports candidate, blockers (exhausted, held labels, cap, mode) and the would-steps, and a - parked candidate's steps start with the by-id claim; + sink candidate's steps start with the by-id claim; - --launch refuses in shadow mode, on a saturated/unknown cap, and on held labels — before creating any session; - a claimed candidate launches end to end: create (location @@ -27,7 +28,7 @@ - a bind failure deletes the created session (no orphan); - a location mismatch deletes the session and checkpoints launch_failed instead of binding; -- a parked candidate whose by-id claim fails launches nothing. +- a sink candidate whose by-id claim fails launches nothing. """ import importlib.util @@ -62,23 +63,24 @@ def claimed_row(**over): return row -def parked_row(**over): - row = claimed_row(status="parked", worker_id=None) +def sink_row(**over): + row = claimed_row(status="handed_off", worker_id=None) row.update(over) return row -def serve(claimed=(), parked=()): +def serve(claimed=(), sink=()): """Patch poll's broker fetches to serve the fixture rows.""" def fetch_claimed(queue): return list(claimed) if queue == QUEUE else [] - def fetch_parked(queue): - return list(parked) if queue == QUEUE else [] + def fetch_handed_off(queue): + return list(sink) if queue == QUEUE else [] return patch.multiple( - poll, fetch_claimed_rows=fetch_claimed, fetch_parked_rows=fetch_parked + poll, fetch_claimed_rows=fetch_claimed, + fetch_handed_off_rows=fetch_handed_off ) @@ -108,11 +110,11 @@ def test_claimed_handed_off_is_candidate(self): self.assertEqual(status, "claimed") self.assertEqual(reasons, []) - def test_parked_handoff_is_candidate(self): - with serve(parked=[parked_row()]): + def test_sink_handoff_is_candidate(self): + with serve(sink=[sink_row()]): row, status, cand, reasons = launch_one.find_row(QUEUE, 777) self.assertTrue(cand) - self.assertEqual(status, "parked") + self.assertEqual(status, "handed_off") def test_bound_row_is_not_candidate_and_says_why(self): row = claimed_row(progress={"lane": "opencode", "stage": "handed_off", @@ -137,8 +139,12 @@ def test_openchamber_lane_row_is_not_candidate(self): self.assertTrue(any("OpenChamber" in r for r in reasons)) def test_genuine_wait_park_is_not_candidate(self): - row = parked_row(progress={"lane": "opencode", "stage": "awaiting_ci"}) - with serve(parked=[row]): + # A genuine wait park (status 'parked') is never a sink + # candidate — even served through the sink fetch, the + # status gate in is_handoff_waiting refuses it (#8234). + row = sink_row(status="parked", + progress={"lane": "opencode", "stage": "awaiting_ci"}) + with serve(sink=[row]): _r, _s, cand, _reasons = launch_one.find_row(QUEUE, 777) self.assertFalse(cand) @@ -150,8 +156,8 @@ def test_missing_task(self): class TestPreflight(unittest.TestCase): - def test_parked_candidate_reports_would_steps(self): - with serve(parked=[parked_row()]), live_and_room(2), \ + def test_sink_candidate_reports_would_steps(self): + with serve(sink=[sink_row()]), live_and_room(2), \ patch.object(launch_one, "hard_stop_reason", return_value=None): out = launch_one.preflight(QUEUE, 777) self.assertTrue(out["candidate"]) @@ -324,9 +330,9 @@ def test_prompt_failure_reports_failure_but_keeps_the_binding(self): self.assertIn("prompt_failed", rec["reason"]) self.assertEqual(deleted, []) # bound session is supervision's, not deleted - def test_parked_candidate_claims_by_id_then_launches(self): + def test_sink_candidate_claims_by_id_then_launches(self): fq = FakeQueue(claim_row={"task": {"id": 777, "worker_id": "opencode-claimant"}}) - rec, _d = self.run_launch(rows_kw={"parked": [parked_row()]}, fq=fq) + rec, _d = self.run_launch(rows_kw={"sink": [sink_row()]}, fq=fq) self.assertTrue(rec["ok"], rec) self.assertEqual(fq.verbs(), ["claim", "bind", "checkpoint"]) claim = fq.calls[0] @@ -336,11 +342,11 @@ def test_parked_candidate_claims_by_id_then_launches(self): checkpoint = fq.calls[2] self.assertIn("opencode-claimant", checkpoint) - def test_parked_claim_failure_launches_nothing(self): + def test_sink_claim_failure_launches_nothing(self): fq = FakeQueue(claim_row=None, claim_rc=1) - rec, deleted = self.run_launch(rows_kw={"parked": [parked_row()]}, fq=fq) + rec, deleted = self.run_launch(rows_kw={"sink": [sink_row()]}, fq=fq) self.assertFalse(rec["ok"]) - self.assertEqual(rec["reason"], "parked_claim_failed") + self.assertEqual(rec["reason"], "sink_claim_failed") self.assertEqual(fq.verbs(), ["claim"]) self.assertEqual(deleted, []) diff --git a/pm-stack/opencode-claimant/test_poll.py b/pm-stack/opencode-claimant/test_poll.py index 3fcbae7132..44e875e7d9 100755 --- a/pm-stack/opencode-claimant/test_poll.py +++ b/pm-stack/opencode-claimant/test_poll.py @@ -173,14 +173,15 @@ def test_unassigned_task_is_not_candidate(self): self.assertFalse(poll.is_candidate(self.row(progress={}))) -class TestIsHandoffParked(unittest.TestCase): - """The handoff sink: a handed-off task parked by its claiming - lane must surface as a candidate, or it loops claim → handoff → - park → re-claim forever (#7907/#6533).""" +class TestIsHandoffWaiting(unittest.TestCase): + """The handoff sink: a handed-off task resting in the sink + (status 'handed_off', #8234) must surface as a candidate, or it + is never collected. Sink membership is the STATUS — no stage + is read here (#8192).""" def row(self, **over): r = { - "status": "parked", + "status": "handed_off", "progress": { "lane": "opencode", "last_checkpoint": {"stage": "handed_off"}, @@ -191,23 +192,41 @@ def row(self, **over): r.update(over) return poll.normalize_row(r) - def test_parked_handoff_is_candidate(self): - self.assertTrue(poll.is_handoff_parked(self.row())) - cands = poll.get_parked_candidates([self.row()]) + def test_sink_handoff_is_candidate(self): + self.assertTrue(poll.is_handoff_waiting(self.row())) + cands = poll.get_handed_off_candidates([self.row()]) self.assertEqual(len(cands), 1) - def test_parked_launch_failed_yield_is_candidate(self): + def test_sink_launch_failed_yield_is_candidate(self): r = self.row(progress={"lane": "opencode", "stage": "launch_failed"}) - self.assertTrue(poll.is_handoff_parked(r)) - - def test_genuine_wait_park_is_not_candidate(self): - # A gated dependency park: stage is the park itself. + self.assertTrue(poll.is_handoff_waiting(r)) + + def test_stage_source_disagreement_is_still_candidate(self): + # #8192 regression: the top-level stage and the last + # checkpoint's stage DISAGREE (top-level advanced past the + # yield). The broker used to read one source and this poll + # the other; since #8234 neither reads a stage for a sink + # row — the status is the membership — so the row is a + # candidate either way. r = self.row( - progress={"lane": "opencode", "stage": "parked", "gate": "#3801 OPEN"} + progress={ + "lane": "opencode", + "stage": "working", + "last_checkpoint": {"stage": "handed_off"}, + "session_id": None, + } ) - self.assertFalse(poll.is_handoff_parked(r)) + self.assertTrue(poll.is_handoff_waiting(r)) - def test_parked_bound_row_is_not_candidate(self): + def test_genuine_wait_park_is_not_candidate(self): + # A 'parked' row is a genuine wait by definition since + # #8234 — even one whose progress is handoff-shaped (a + # recorded handoff that later took a real triage wait, + # task 10995's shape). The status decides, not the shape. + r = self.row(status="parked") + self.assertFalse(poll.is_handoff_waiting(r)) + + def test_sink_bound_row_is_not_candidate(self): r = self.row( progress={ "lane": "opencode", @@ -215,15 +234,15 @@ def test_parked_bound_row_is_not_candidate(self): "session_id": "ses_1", } ) - self.assertFalse(poll.is_handoff_parked(r)) + self.assertFalse(poll.is_handoff_waiting(r)) - def test_claimed_row_is_not_a_parked_candidate(self): + def test_claimed_row_is_not_a_sink_candidate(self): r = self.row(status="claimed") - self.assertFalse(poll.is_handoff_parked(r)) + self.assertFalse(poll.is_handoff_waiting(r)) - def test_parked_openchamber_lane_is_never_candidate(self): + def test_sink_openchamber_lane_is_never_candidate(self): r = self.row(lane_id="8d133595-c60c-4dcb-8e82-59b7d0ac9b5a") - self.assertFalse(poll.is_handoff_parked(r)) + self.assertFalse(poll.is_handoff_waiting(r)) class TestParseLeaseMs(unittest.TestCase):