From af68be5988229ca0e0cca7236bd4fd9346ef967a Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:49:52 -0600 Subject: [PATCH 1/4] fleet-queue: Turso backend for the queue core (muse-queue) behind QUEUE_BROKER_BACKEND (#6741) The queue core was the one #5689 piece kept on Postgres; with the muse-dev2 data plane down (#6619) it had no live home. This adds a dedicated-Turso backend to the queue-broker: same protocol and envelopes, no client changes, Postgres remains the default until the cutover runbook flips the unit env. Semantics reconstructed from the recovered PG function bodies (pm-stack/opencode-claimant/migration-0021..0024.sql): claim as one conditional UPDATE (libSQL single-writer atomicity; competing claim returns {row: null}, exit 5), expire_leases, fail backoff 900s/2700s, park ready-condition/wait_kind mapping, lane balancing, bind live-lease guard. Verbs whose PG bodies were not recovered are implemented to the broker contract and marked. Schema ensured at broker startup against the dedicated muse-queue DB (org dezren39, group great-star-lord; rw token via BWS turso.muse-queue-rw-token). Proven live 2026-11-07T03:46Z against the real DB: enqueue -> claim A -> claim B refused (exit 5) -> lane/bind/heartbeat (foreign heartbeat refused) -> checkpoint -> complete; lease-expiry reclaim by a second worker after a 2s lease lapsed. Runbook + deviations + the post-cutover Postgres remainder inventory: doc/fleet/queue-turso-cutover.md. --- doc/fleet/queue-turso-cutover.md | 219 +++ pkgs/fleet/crates/fleet-queue/src/lib.rs | 2 + .../crates/fleet-queue/src/queue_broker.rs | 65 + .../crates/fleet-queue/src/turso_queue.rs | 1693 +++++++++++++++++ 4 files changed, 1979 insertions(+) create mode 100644 doc/fleet/queue-turso-cutover.md create mode 100644 pkgs/fleet/crates/fleet-queue/src/turso_queue.rs diff --git a/doc/fleet/queue-turso-cutover.md b/doc/fleet/queue-turso-cutover.md new file mode 100644 index 0000000000..b41eff82e3 --- /dev/null +++ b/doc/fleet/queue-turso-cutover.md @@ -0,0 +1,219 @@ +# Queue core on Turso — cutover runbook (#6741) + +**Status:** backend BUILT and PROVEN live 2026-11-06; production +broker still on Postgres (default unchanged). Cutover = the env +flip in step 2 below, executed as its own change. + +**Why:** the queue core (`agent.tasks`, `leases`, `lanes`, +`workers`, `checkpoints`, `repo_task_lane_ledger`) was the one +piece of the #5689/#5690-series migration deliberately kept on +Postgres. When the muse-dev2 data plane went down on 2026-11-06 +(#6619, Supabase platform fault), it had no live home; the GitHub +fallback mode (`queue-fallback-mode.md`) carried the work. Drew +ordered the dedicated Turso replacement the same evening. + +## What exists + +- **Database:** Turso `muse-queue` (org dezren39, group + great-star-lord, aws-us-east-1, id + `01a1b414-2d01-7c27-8a43-783bb5b09296`, + `libsql://muse-queue-dezren39.aws-us-east-1.turso.io`). RW token + vaulted in BWS as `turso.muse-queue-rw-token` (the + muse-mirror/muse-platform pattern; BWS only — those tokens have + no 1Password copies either), verified by live readback. +- **Backend:** `pkgs/fleet/crates/fleet-queue/src/turso_queue.rs`, + behind the existing broker protocol — no client changes. + Selection is the broker's config: `QUEUE_BROKER_BACKEND=turso` + (default `postgres`), `QUEUE_BROKER_TURSO_URL`, + `QUEUE_BROKER_TURSO_TOKEN_FILE` (else the secrets broker resolves + `turso.muse-queue-rw-token`). Schema is ensured idempotently at + broker startup. +- **Schema** (canonical copy = the `SCHEMA` const in + turso_queue.rs): `tasks` (all PG columns the verbs touch, JSON + columns stored as TEXT and parsed back on read), `leases`, + `lanes`, `workers`, `checkpoints`, `repo_task_lane_ledger`, + `events`; unique `(queue, dedupe_key)` index; claim-scan index. +- **Semantics** are reconstructed from the recovered live PG + function bodies (`pm-stack/opencode-claimant/migration-0021.sql` + ..`migration-0024.sql`): claim (incl. parked resume without an + attempts increment, lane validation, binding clearing), + expire_leases, fail (900 s / 2700 s requeue backoff), park + (ready-condition + wait_kind mapping), lane assignment + (opencode/direct balancing), bind (live-lease guard). A claim is + one conditional UPDATE — libSQL's single-writer serialization is + the atomicity; a competing claim matches no row and returns + `{row: null}` (client exit 5), the PG envelope. + +## Proof (2026-11-07T03:46–03:47Z, broker on 127.0.0.1:14801) + +Against the real `muse-queue` DB, through the real client verbs: + +1. Health (empty): `project: muse-queue-dezren39.aws-us-east-1.turso.io (resolved via turso)`. +2. Enqueue of the labeled migration-proof packet → task 1, queued. +3. Claim by `turso-proof-a` → claimed, lease +45 min, attempts 1. +4. Claim by `turso-proof-b` → refused: `{"task": null}`, exit 5. +5. Lane assign → ledger row, `assigned_lane=opencode`; + bind → session stamped; heartbeat by B → refused + (`task 1 is not claimed by turso-proof-b`, exit 5); + heartbeat by A → lease extended; checkpoint → row in + `checkpoints` (stage `proof-midpoint`); complete → `done`. +6. Lease expiry: task 2 claimed by `turso-proof-c` with a 2 s + lease; `turso-proof-d` refused immediately, then claimed the + task after expiry (attempts 2) and completed it. +7. Final health: queue `repo-health-code-shadow` — 2 done, + 0 queued/claimed. Every state above was also read back from + the DB directly (tasks/leases/checkpoints/ledger/workers/events). + +## Cutover steps + +1. **Binary:** land a fleet build carrying this backend through + the normal build/pin path. (The nix build is currently broken + by #6725 — cargo vendor missing `sha2`; until it is fixed, the + fastlane drop-in pattern from #6658 is the interim route.) + Verify the installed binary answers `fleet queue health` + against a Turso-backed test broker on a side port (as in the + proof) before touching the production broker. +2. **Flip:** set `QUEUE_BROKER_BACKEND=turso` in the queue-broker + unit env on the laptop and restart the unit. Nothing else + changes: clients, claimant, and worker runbooks already speak + only to the broker. **Drain decision first:** the Turso queue + starts empty. Either (a) flip while the GitHub fallback is + carrying work (PG is down anyway — there is nothing to drain + until PG returns), or (b) if PG has returned, let PG claims + drain to zero, export any open queued/parked/blocked PG tasks, + and re-enqueue them into Turso preserving dedupe keys. Option + (a) is the expected path while #6619 is open. +3. **Verify:** `fleet queue health` names the Turso host; run one + labeled proof cycle (the #6741 packet shape) on the production + broker; watch the first real lane claims land in the Turso + `events` table. +4. **Soak:** GitHub fallback mode stays ACTIVE as the bridge + until the Turso broker has carried a full day of real claims; + workers keep routing to fallback whenever `fleet queue health` + fails, per runbook §0a. + +## Interaction with the PG staged-recovery sequence + +**Unaffected.** If Postgres returns before cutover, the staged +sequence still runs in its order — outbox reconciliation (17) → +monitor requeue (16) → 142-at-cap requeue → migration finalize +scripts (`migrate_slice6_mirror.py`, then `finalize_pg.py`). The +requeues target the PG queue; if the flip (step 2) has already +happened when PG returns, run the export half of the finalize +scripts and the mirror drops, but skip the requeues — the work +they would revive is re-enqueued into Turso per step 2(b) or has +already been carried by the fallback. + +## Rollback + +Set `QUEUE_BROKER_BACKEND=postgres` (or remove it) and restart +the broker unit. The Turso backend never writes to Postgres and +the Postgres backend never writes to Turso; PG data is untouched +by a Turso soak. Tasks claimed in Turso during a soak stay in +Turso — on rollback, let them finish or expire there (claims are +visible in the Turso `tasks`/`events` tables) before declaring +the rollback complete. + +## Deviations from the PG behavior (complete list) + +1. `agent.events`: PG writes it in the same transaction as each + queue transition, with an FK to `tasks(id)`, and the + `repo_queue_health` view joins it for terminal counters. The + Turso backend writes its own `events` table (no FK — libSQL + enforces none here) and health counts task statuses directly; + there are no `terminal_events_24h/7d` fields. +2. `repo_queue_health`'s exact PG column set was not recovered; + Turso health returns per-queue status counts + total + + `oldest_queued_at`. The client renders whatever columns the + first row carries, so this is wire-compatible. +3. `expire_leases` runs inside claim (as in PG's claim body). + PG additionally had a pg_cron job calling it every minute; + there is no standalone Turso sweeper yet — leases also clear + lazily on the next claim. Follow-up. +4. `revalidate_parked_tasks` (PG pg_cron, daily) is NOT ported: + parked tasks with non-time ready conditions do not auto-release + in Turso mode yet. Time parks release through claim at + `not_before`, as in PG. Follow-up. +5. `prune_events` (30-day retention) is not ported; the Turso + `events` table grows unbounded until it is. Follow-up. +6. Enqueue dedupe returns the existing row as-is; PG's + revive-on-dedupe nuance (inferred from the client's outcome + wording) was not fully recovered. +7. `heartbeat_task`, `checkpoint_task`, `block_task`, + `complete_task`, `cancel_repo_task`, and + `record_repo_task_lane_execution` bodies were not recovered; + they are implemented to the broker/client contract (owner-only + transitions, progress/result merges, ledger execution upsert) + and are marked as such in the code. +8. Timestamps are second-resolution ISO-8601 UTC strings (PG + `timestamptz` carries sub-second precision); ordering is + lexicographic = chronological. +9. Task ids are per-database autoincrements starting at 1. PG + task ids do not carry over; references to them remain PG + history. +10. Priorities: NULL priorities sort last on claim/list (PG ASC + default); packets are validated to always carry one, so this + only affects hand-written rows. + +## What still touches Postgres after the queue cutover + +The delete-the-project checklist. Nothing below was moved or +dropped by #6741. + +- **agent.events (PG stream, ~196k rows, FK → tasks)** — its + queue-transition writers are replaced by the Turso `events` + table at cutover; what remains is the historical stream plus + its pg_cron consumers (below). Moving takes: port or retire + prune/revalidate, confirm no direct readers remain, then + export-or-abandon per the #5690 append-stream class. +- **pg_cron jobs** (`agent-expire-leases` every minute, + `agent-prune-events` daily, `park-revalidation-daily`) — they + die with the project. Expire is covered inside claim; prune + (30-day retention) and park revalidation need small ports to a + broker-side periodic task (deviations 4–5). +- **ci.events + the `github-ci` Edge Function** — the writer runs + ON Supabase (Edge Functions), upserts PG, and dual-writes Turso + `ci_events` (live since 2026-11-06). The morning-readout reader + still reads PG (`ci.recent_failures`). Moving takes: re-home + the webhook receiver off Edge Functions and flip the reader to + Turso (flip criteria already staged: one verified real delivery + landing in `ci_events`). +- **agent.mirror_\* PG originals (28 tables)** — verified shadows + live in Turso `muse-mirror`; the PG copies remain the target of + the **paused runtime-db-export cron**, whose loader still points + at PG. Retiring takes: repoint that loader to `muse-mirror` + BEFORE any unpause (standing hazard, recorded on #5691), then + the staged `finalize_pg.py` drops (28 tables). +- **Slice-2 sheet staging + curated copies (#5692)** — Turso + shadows landed; consumer cutovers pending. Separately, the + ainventory relational core (`models`, `measurement_events`, + `price_events`, `provider_policies`, `benchmark_results` + the + views over them) is KEEP-on-Postgres BY DESIGN — not a leftover; + deleting the project needs a deliberate re-home decision for + that core. +- **Slice-1 `sources` remainder (#5695)** — 5 rows exist only in + PG (`automation`/`finance`/`home`/`research` sources; D1 + `muse-config` holds the other 49 of 54). Moving takes one PG + read at recovery + the D1 insert; then the 4 slice-1 Turso + config shadows drop per the finalize script. +- **automation.events** — orchestration passes append via + `automation_append.py`; appends have failed since the outage. + Moving takes repointing that helper to a Turso events home + (the #5690 stream class) — not yet done. +- **agent.external_comms** — the external-comms send-time ledger + (`pm-stack/external-comms/record-external-send`) writes PG. + Moving takes a Turso table + a script repoint. +- **pm-stack aggregator** (`src/supabase.ts`, + `scripts/collect-fleet-feed.ts`) — a live reader of muse-dev2 + behind the fleet feed. Moving takes an audit of its exact + tables and a repoint to the Turso shadows. +- **PG-bound tooling** — `supabase-exec` helper, the + `pm-stack/supabase-export` quota script, and every consumer of + the `supabase.muse-dev2.*` secret names: retire or repoint with + their consumers, last. +- **Supabase platform schemas (auth 27, storage 10, realtime 3, + vault 1 — the 41-table RETIRE class)** — no fleet consumer was + found in the audits; the only platform dependency is Edge + Functions hosting (the `github-ci` receiver above). Re-home + that function first; nothing else needs moving, and deleting + the project is what retires these. diff --git a/pkgs/fleet/crates/fleet-queue/src/lib.rs b/pkgs/fleet/crates/fleet-queue/src/lib.rs index 711e813e7d..55222c25cc 100644 --- a/pkgs/fleet/crates/fleet-queue/src/lib.rs +++ b/pkgs/fleet/crates/fleet-queue/src/lib.rs @@ -31,6 +31,8 @@ pub mod client; pub mod fallback; #[cfg(feature = "queue-broker")] pub mod queue_broker; +#[cfg(feature = "queue-broker")] +pub mod turso_queue; #[cfg(feature = "secrets-broker")] pub mod secrets_broker; #[cfg(any(feature = "queue-broker", feature = "secrets-broker"))] diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 7d6f03f25c..6e4a7c29c4 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -15,6 +15,13 @@ //! QUEUE_BROKER_TOKEN_FILE (default ~/.config/queue-broker/token), //! QUEUE_BROKER_SECRETS_URL (default http://100.99.113.103:4800), //! QUEUE_BROKER_SECRETS_TOKEN_FILE (default ~/.config/secrets-broker/token). +//! +//! Backend (#6741): QUEUE_BROKER_BACKEND=postgres (default; the +//! Supabase PostgREST path above) or =turso — the queue core on the +//! dedicated Turso DB `muse-queue` (crate::turso_queue), selected by +//! QUEUE_BROKER_TURSO_URL / QUEUE_BROKER_TURSO_TOKEN_FILE. The +//! production default does not flip with the code; cutover is +//! doc/fleet/queue-turso-cutover.md. use std::sync::{Arc, Mutex, RwLock}; use std::time::{Duration, Instant}; @@ -77,6 +84,9 @@ struct State { health_cache: RwLock>, enqueue_gate: Mutex, failure_events_path: Option, + /// #6741: Some when QUEUE_BROKER_BACKEND=turso; dispatch routes + /// every verb except /validate + /healthz to the Turso backend. + turso: Option, } struct BErr { @@ -501,6 +511,11 @@ fn verb_with_execution(st: &State, fn_name: &str, args: Value, req: &Value) -> V } fn dispatch(st: &State, path: &str, req: &Value) -> Value { + if let Some(t) = &st.turso { + if path != "/validate" && path != "/healthz" { + return crate::turso_queue::dispatch(t, path, req); + } + } match path { "/validate" => { let packet = req.get("packet").cloned().unwrap_or(Value::Null); @@ -857,6 +872,55 @@ pub fn run() -> i32 { let _ = std::fs::create_dir_all(dir); } + // #6741 backend selection: Postgres stays the default; the + // Turso backend is opt-in per broker process until the cutover + // runbook flips the unit env. + let turso = if std::env::var("QUEUE_BROKER_BACKEND") + .map(|v| v.eq_ignore_ascii_case("turso")) + .unwrap_or(false) + { + let url = std::env::var("QUEUE_BROKER_TURSO_URL") + .unwrap_or_else(|_| crate::turso_queue::DEFAULT_TURSO_URL.to_string()); + let token = match std::env::var("QUEUE_BROKER_TURSO_TOKEN_FILE") { + Ok(f) => crate::token_file::load_token_file(&f).unwrap_or_else(|e| { + crate::log::info("queue-broker", &e); + std::process::exit(3); + }), + Err(_) => { + let resolver = Resolver::new(vec![Box::new(DirectSecrets { + url: secrets_url.clone(), + token: secrets_token.clone(), + agent: agent.clone(), + })]); + resolver + .resolve(crate::turso_queue::TURSO_TOKEN_SECRET_NAME) + .map(|v| v.expose().to_string()) + .unwrap_or_else(|e| { + crate::log::info( + "queue-broker", + &format!("turso backend token resolve failed: {e}"), + ); + std::process::exit(3); + }) + } + }; + let backend = crate::turso_queue::TursoBackend::new(url, token, agent.clone()); + backend.ensure_schema().unwrap_or_else(|e| { + crate::log::info( + "queue-broker", + &format!("turso backend schema ensure failed: {e}"), + ); + std::process::exit(3); + }); + crate::log::info( + "queue-broker", + &format!("queue backend: turso ({})", backend.url()), + ); + Some(backend) + } else { + None + }; + let state = Arc::new(State { secrets_url, secrets_token, @@ -865,6 +929,7 @@ pub fn run() -> i32 { health_cache: RwLock::new(None), enqueue_gate: Mutex::new(EnqueueGate::new()), failure_events_path: Some(failure_events_path), + turso, }); let server = Server::http(&bind).unwrap_or_else(|e| { diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs new file mode 100644 index 0000000000..3feee17594 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -0,0 +1,1693 @@ +//! queue-broker Turso backend — the queue core on libSQL (#6741). +//! +//! The Postgres queue core (agent.tasks / leases / lanes / workers / +//! checkpoints / repo_task_lane_ledger / events in muse-dev2) was the +//! one piece of the 2026-11-04..06 migration (#5689/#5690 series) +//! deliberately kept on Postgres for transactional coupling. When +//! the muse-dev2 data plane went down on 2026-11-06 (#6619, Supabase +//! platform fault) the queue core had no live home; the GitHub +//! fallback mode (doc/fleet/queue-fallback-mode.md) carried the work. +//! This module is the dedicated-Turso replacement Drew ordered the +//! same evening: a dedicated database (`muse-queue`, org dezren39, +//! group great-star-lord; rw token in BWS as +//! `turso.muse-queue-rw-token`) behind the SAME broker protocol, so +//! no client changes: backend selection is the broker's config. +//! +//! Selection: `QUEUE_BROKER_BACKEND=turso` (default `postgres` — the +//! production default does NOT flip with this code; cutover is the +//! runbook in doc/fleet/queue-turso-cutover.md). URL: +//! `QUEUE_BROKER_TURSO_URL` (default the muse-queue HTTPS URL). +//! Token: `QUEUE_BROKER_TURSO_TOKEN_FILE`, else the secrets broker +//! by the name above. +//! +//! Schema + semantics are reconstructed from the recovered live PG +//! function bodies in pm-stack/opencode-claimant/migration-0021.sql +//! .. migration-0024.sql (claim_repo_task, fail_repo_task, park_task, +//! expire_leases, assign_repo_task_lane, +//! bind_repo_task_lane_session) plus the broker/client contract in +//! this crate for the verbs whose PG bodies were not recovered +//! (enqueue dedupe, heartbeat, checkpoint, block, complete, cancel, +//! record execution, health aggregation). Every deviation from the +//! PG behavior is listed in the cutover runbook. +//! +//! Atomicity: libSQL is single-writer. A claim is ONE conditional +//! UPDATE whose WHERE clause re-checks claimability (status in +//! queued/parked with a due not_before, attempts left) against the +//! row a subquery picks — the same shape as PG's FOR UPDATE SKIP +//! LOCKED pick, with the write serialization libSQL already +//! guarantees. A competing claim after the first lands matches no +//! row and returns `{row: null}` (client exit 5), exactly the PG +//! envelope. + +use serde_json::{Map, Value, json}; + +use crate::validate::{task_from_packet, validate_packet}; + +pub const DEFAULT_TURSO_URL: &str = "https://muse-queue-dezren39.aws-us-east-1.turso.io"; +pub const TURSO_TOKEN_SECRET_NAME: &str = "turso.muse-queue-rw-token"; + +const TASK_COLS: &str = "id, queue, title, body, payload, dedupe_key, priority, status, \ + not_before, worker_id, claimed_at, lease_until, lane_id, attempts, max_attempts, \ + progress, result, last_error, park_kind, wait_kind, ready_condition, \ + last_checked_at, check_outcome, created_at, updated_at"; +const LEDGER_COLS: &str = "id, queue, task_id, assigned_lane, executed_lane, \ + exclusion_reason, assigned_by, session_id, launched_by, fallback_reason, \ + created_at, updated_at"; +/// Task columns whose stored TEXT is JSON (PG jsonb) — parsed back +/// into values so the wire shape matches the Postgres broker's. +const TASK_JSON_COLS: [&str; 4] = ["payload", "progress", "result", "ready_condition"]; + +// --------------------------------------------------------------------------- +// Time (no chrono in this crate: ISO-8601 UTC strings, lexicographic +// order == chronological order, the same trick the list/claim SQL +// relies on) +// --------------------------------------------------------------------------- + +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719_468; + let era = if z >= 0 { z } else { z - 146_096 } / 146_097; + let doe = (z - era * 146_097) as u64; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe as i64 + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +pub fn iso(unix: i64) -> String { + let days = unix.div_euclid(86_400); + let secs = unix.rem_euclid(86_400); + let (y, m, d) = civil_from_days(days); + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + secs / 3600, + (secs % 3600) / 60, + secs % 60 + ) +} + +fn now_unix() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +fn now_iso() -> String { + iso(now_unix()) +} + +fn after_iso(secs: i64) -> String { + iso(now_unix() + secs) +} + +// --------------------------------------------------------------------------- +// libSQL HTTP pipeline client (same wire as fleet-dispatch-test, #6580) +// --------------------------------------------------------------------------- + +enum Arg { + Text(String), + Int(i64), + Null, +} + +impl Arg { + fn to_json(&self) -> Value { + match self { + Arg::Text(v) => json!({"type": "text", "value": v}), + Arg::Int(v) => json!({"type": "integer", "value": v.to_string()}), + Arg::Null => json!({"type": "null"}), + } + } +} + +fn arg_str(v: Option<&str>) -> Arg { + v.map(|s| Arg::Text(s.to_string())).unwrap_or(Arg::Null) +} + +fn arg_json(v: &Value) -> Arg { + if v.is_null() { + Arg::Null + } else { + Arg::Text(v.to_string()) + } +} + +struct StmtResult { + cols: Vec, + rows: Vec>, + affected: u64, + last_insert_rowid: Option, +} + +fn cell_to_json(cell: &Value) -> Value { + let ty = cell.get("type").and_then(|t| t.as_str()).unwrap_or("null"); + let raw = cell.get("value"); + match ty { + "text" => raw + .and_then(|v| v.as_str()) + .map(|s| Value::String(s.to_string())) + .unwrap_or(Value::Null), + "integer" => raw + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .map(|n| json!(n)) + .unwrap_or(Value::Null), + "float" => raw + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .and_then(serde_json::Number::from_f64) + .map(Value::Number) + .unwrap_or(Value::Null), + _ => Value::Null, + } +} + +pub struct TursoBackend { + url: String, + token: String, + agent: ureq::Agent, +} + +type TErr = String; + +impl TursoBackend { + pub fn new(url: String, token: String, agent: ureq::Agent) -> Self { + Self { + url: url.trim_end_matches('/').to_string(), + token, + agent, + } + } + + pub fn url(&self) -> &str { + &self.url + } + + fn pipeline(&self, stmts: &[(&str, Vec)]) -> Result, TErr> { + let mut requests: Vec = stmts + .iter() + .map(|(sql, args)| { + json!({ + "type": "execute", + "stmt": { + "sql": sql, + "args": args.iter().map(|a| a.to_json()).collect::>(), + } + }) + }) + .collect(); + requests.push(json!({"type": "close"})); + let body = json!({"requests": requests}); + let auth = format!("Bearer {}", self.token); + let mut resp = self + .agent + .post(&format!("{}/v2/pipeline", self.url)) + .header("Authorization", &auth) + .header("Content-Type", "application/json") + .send(serde_json::to_string(&body).unwrap_or_default().as_str()) + .map_err(|e| format!("turso queue store unreachable: {e}"))?; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("cannot read turso response: {e}"))?; + if !(200..300).contains(&status) { + let snippet: String = text.chars().take(300).collect(); + return Err(format!("turso queue store HTTP {status}: {snippet}")); + } + let parsed: Value = serde_json::from_str(&text) + .map_err(|e| format!("turso answered a non-JSON body: {e}"))?; + if let Some(err) = parsed.get("error") { + let msg = match err { + Value::String(s) => s.clone(), + other => other + .get("message") + .and_then(|m| m.as_str()) + .map(str::to_string) + .unwrap_or_else(|| other.to_string()), + }; + return Err(format!("turso pipeline error: {msg}")); + } + let results = parsed + .get("results") + .and_then(|r| r.as_array()) + .ok_or("turso pipeline response has no results")?; + let mut out = Vec::new(); + for (i, r) in results.iter().enumerate() { + if r.get("response") + .and_then(|x| x.get("type")) + .and_then(|t| t.as_str()) + == Some("close") + { + continue; + } + if r.get("type").and_then(|t| t.as_str()) != Some("ok") { + let msg = r + .get("error") + .and_then(|e| match e { + Value::String(s) => Some(s.clone()), + other => other + .get("message") + .and_then(|m| m.as_str()) + .map(str::to_string), + }) + .unwrap_or_else(|| "unknown turso error".to_string()); + return Err(format!("turso statement {} failed: {msg}", i + 1)); + } + let result = r + .get("response") + .and_then(|x| x.get("result")) + .ok_or("turso pipeline response has no result")?; + let cols = result + .get("cols") + .and_then(|c| c.as_array()) + .map(|cols| { + cols.iter() + .map(|c| { + c.get("name") + .and_then(|n| n.as_str()) + .unwrap_or("") + .to_string() + }) + .collect() + }) + .unwrap_or_default(); + let rows = result + .get("rows") + .and_then(|r| r.as_array()) + .map(|rows| { + rows.iter() + .map(|row| { + row.as_array() + .map(|cells| cells.iter().map(cell_to_json).collect()) + .unwrap_or_default() + }) + .collect() + }) + .unwrap_or_default(); + out.push(StmtResult { + cols, + rows, + affected: result + .get("affected_row_count") + .and_then(|n| n.as_u64()) + .unwrap_or(0), + last_insert_rowid: result + .get("last_insert_rowid") + .and_then(|n| n.as_str()) + .and_then(|s| s.parse::().ok()), + }); + } + Ok(out) + } + + fn exec(&self, sql: &str, args: &[Arg]) -> Result { + Ok(self.pipeline(&[(sql, args.to_vec())])?.into_iter().next().unwrap()) + } + + /// Rows of one SELECT as JSON objects, with the given TEXT + /// columns parsed back into JSON values. + fn query_objs( + &self, + sql: &str, + args: &[Arg], + json_cols: &[&str], + ) -> Result, TErr> { + let r = self.exec(sql, args)?; + Ok(r.rows + .iter() + .map(|row| { + let mut obj = Map::new(); + for (i, col) in r.cols.iter().enumerate() { + let mut v = row.get(i).cloned().unwrap_or(Value::Null); + if json_cols.contains(&col.as_str()) { + if let Value::String(s) = &v { + v = serde_json::from_str(s).unwrap_or(Value::Null); + } + } + obj.insert(col.clone(), v); + } + Value::Object(obj) + }) + .collect()) + } + + pub fn ensure_schema(&self) -> Result<(), TErr> { + let stmts: Vec<(&str, Vec)> = SCHEMA.iter().map(|s| (*s, Vec::new())).collect(); + self.pipeline(&stmts)?; + Ok(()) + } +} + +// Arg is cloned into pipeline bodies; derive Clone via manual impl +// (the enum is small and the values are request-scoped). +impl Clone for Arg { + fn clone(&self) -> Self { + match self { + Arg::Text(s) => Arg::Text(s.clone()), + Arg::Int(n) => Arg::Int(*n), + Arg::Null => Arg::Null, + } + } +} + +const SCHEMA: [&str; 10] = [ + "CREATE TABLE IF NOT EXISTS tasks (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, \ + queue TEXT NOT NULL, title TEXT, body TEXT, \ + payload TEXT NOT NULL DEFAULT '{}', dedupe_key TEXT, \ + priority INTEGER, status TEXT NOT NULL DEFAULT 'queued', \ + not_before TEXT, worker_id TEXT, claimed_at TEXT, lease_until TEXT, \ + lane_id TEXT, attempts INTEGER NOT NULL DEFAULT 0, \ + max_attempts INTEGER NOT NULL DEFAULT 4, \ + progress TEXT NOT NULL DEFAULT '{}', result TEXT NOT NULL DEFAULT '{}', \ + last_error TEXT, park_kind TEXT, wait_kind TEXT, ready_condition TEXT, \ + last_checked_at TEXT, check_outcome TEXT, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", + "CREATE UNIQUE INDEX IF NOT EXISTS tasks_queue_dedupe \ + ON tasks(queue, dedupe_key) WHERE dedupe_key IS NOT NULL", + "CREATE INDEX IF NOT EXISTS tasks_claim_scan \ + ON tasks(queue, status, priority, created_at)", + "CREATE TABLE IF NOT EXISTS leases (\ + task_id INTEGER PRIMARY KEY, worker_id TEXT NOT NULL, \ + lease_until TEXT NOT NULL, heartbeat_at TEXT NOT NULL)", + "CREATE TABLE IF NOT EXISTS lanes (\ + lane_id TEXT PRIMARY KEY, worker_id TEXT NOT NULL, \ + queue TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1)", + "CREATE TABLE IF NOT EXISTS workers (\ + worker_id TEXT PRIMARY KEY, last_seen_at TEXT NOT NULL, \ + current_task_id INTEGER)", + "CREATE TABLE IF NOT EXISTS checkpoints (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, \ + worker_id TEXT NOT NULL, stage TEXT NOT NULL, \ + progress TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL)", + "CREATE TABLE IF NOT EXISTS repo_task_lane_ledger (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, queue TEXT NOT NULL, \ + task_id INTEGER NOT NULL UNIQUE, assigned_lane TEXT, executed_lane TEXT, \ + exclusion_reason TEXT, assigned_by TEXT, session_id TEXT, \ + launched_by TEXT, fallback_reason TEXT, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", + "CREATE TABLE IF NOT EXISTS events (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, worker_id TEXT, task_id INTEGER, \ + kind TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '{}', \ + created_at TEXT NOT NULL)", + "CREATE INDEX IF NOT EXISTS events_task ON events(task_id, id)", +]; + +// --------------------------------------------------------------------------- +// Envelope (identical shapes to the Postgres broker dispatch) +// --------------------------------------------------------------------------- + +fn ok(fields: Value) -> Value { + let mut m = json!({"ok": true}); + if let (Some(dst), Some(src)) = (m.as_object_mut(), fields.as_object()) { + for (k, v) in src { + dst.insert(k.clone(), v.clone()); + } + } + m +} + +fn fail(exit: i32, msg: impl Into) -> Value { + json!({"ok": false, "exit": exit, "error": msg.into()}) +} + +fn terr(e: TErr) -> Value { + // Transport/store failures mirror the Postgres broker's exit 4. + fail(4, e) +} + +// --------------------------------------------------------------------------- +// Shared helpers +// --------------------------------------------------------------------------- + +fn merge_obj(base: &Value, patch: &Value) -> Value { + let mut out = match base { + Value::Object(m) => m.clone(), + _ => Map::new(), + }; + if let Value::Object(p) = patch { + for (k, v) in p { + out.insert(k.clone(), v.clone()); + } + } + Value::Object(out) +} + +fn get_task(t: &TursoBackend, id: i64) -> Result, TErr> { + let rows = t.query_objs( + &format!("SELECT {TASK_COLS} FROM tasks WHERE id = ?"), + &[Arg::Int(id)], + &TASK_JSON_COLS, + )?; + Ok(rows.into_iter().next()) +} + +fn get_ledger(t: &TursoBackend, task_id: i64) -> Result, TErr> { + let rows = t.query_objs( + &format!( + "SELECT {LEDGER_COLS} FROM repo_task_lane_ledger WHERE task_id = ?" + ), + &[Arg::Int(task_id)], + &[], + )?; + Ok(rows.into_iter().next()) +} + +fn event( + t: &TursoBackend, + worker: Option<&str>, + task_id: Option, + kind: &str, + detail: &Value, +) -> Result<(), TErr> { + t.exec( + "INSERT INTO events (worker_id, task_id, kind, detail, created_at) \ + VALUES (?, ?, ?, ?, ?)", + &[ + arg_str(worker), + task_id.map(Arg::Int).unwrap_or(Arg::Null), + Arg::Text(kind.to_string()), + Arg::Text(detail.to_string()), + Arg::Text(now_iso()), + ], + )?; + Ok(()) +} + +fn touch_worker(t: &TursoBackend, worker: &str, task_id: Option) -> Result<(), TErr> { + t.exec( + "INSERT INTO workers (worker_id, last_seen_at, current_task_id) VALUES (?, ?, ?) \ + ON CONFLICT(worker_id) DO UPDATE SET last_seen_at = excluded.last_seen_at, \ + current_task_id = COALESCE(excluded.current_task_id, workers.current_task_id)", + &[ + Arg::Text(worker.to_string()), + Arg::Text(now_iso()), + task_id.map(Arg::Int).unwrap_or(Arg::Null), + ], + )?; + Ok(()) +} + +/// Remove a session binding from a progress object the way migration +/// 0023 does: drop session_id/launched_by, stamp session_cleared. +/// Returns (new progress, cleared session id). +fn clear_binding(progress: &Value, via: &str) -> (Value, Option) { + let old = progress + .get("session_id") + .and_then(|s| s.as_str()) + .map(str::to_string); + match old { + None => (progress.clone(), None), + Some(old) => { + let mut p = match progress { + Value::Object(m) => m.clone(), + _ => Map::new(), + }; + p.remove("session_id"); + p.remove("launched_by"); + p.insert( + "session_cleared".to_string(), + json!({"session_id": old, "cleared_at": now_iso(), "via": via}), + ); + (Value::Object(p), Some(old)) + } + } +} + +fn on_binding_cleared( + t: &TursoBackend, + worker: &str, + task_id: i64, + old_session: &str, + via: &str, +) -> Result<(), TErr> { + t.exec( + "UPDATE repo_task_lane_ledger SET session_id = NULL, updated_at = ? \ + WHERE task_id = ? AND session_id IS NOT NULL", + &[Arg::Text(now_iso()), Arg::Int(task_id)], + )?; + event( + t, + Some(worker), + Some(task_id), + "session_binding_cleared", + &json!({"session_id": old_session, "via": via}), + ) +} + +/// expire_leases (migration 0023 §1): claimed rows whose lease has +/// lapsed return to queued, binding cleared, lease rows dropped. +fn expire_leases(t: &TursoBackend) -> Result<(), TErr> { + let now = now_iso(); + let rows = t.query_objs( + &format!( + "SELECT {TASK_COLS} FROM tasks \ + WHERE status = 'claimed' AND lease_until < ?" + ), + &[Arg::Text(now.clone())], + &TASK_JSON_COLS, + )?; + for row in &rows { + let id = row.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + let worker = row + .get("worker_id") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let progress = row.get("progress").cloned().unwrap_or(json!({})); + let (progress, cleared) = clear_binding(&progress, "expire_leases"); + let upd = t.exec( + "UPDATE tasks SET status = 'queued', worker_id = NULL, lease_until = NULL, \ + progress = ?, updated_at = ? \ + WHERE id = ? AND status = 'claimed' AND lease_until < ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now.clone()), + Arg::Int(id), + Arg::Text(now.clone()), + ], + )?; + if upd.affected == 0 { + continue; + } + event( + t, + Some(&worker), + Some(id), + "lease_expired", + &json!({"via": "expire_leases", "cleared_session_id": cleared}), + )?; + if let Some(old) = cleared { + on_binding_cleared(t, &worker, id, &old, "expire_leases")?; + } + } + t.exec( + "DELETE FROM leases WHERE lease_until < ?", + &[Arg::Text(now)], + )?; + Ok(()) +} + +/// record_repo_task_lane_execution, contract-shaped: stamp the +/// executed lane (+ fallback reason / session) onto the task's +/// ledger row, creating a minimal row when assignment never ran. +fn record_execution(t: &TursoBackend, req: &Value, row: &Value) -> Result, TErr> { + let Some(ex) = req.get("execution").filter(|e| e.is_object()) else { + return Ok(None); + }; + let task_id = req.get("task_id").and_then(|v| v.as_i64()).unwrap_or(0); + let queue = row + .get("queue") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let now = now_iso(); + if get_ledger(t, task_id)?.is_some() { + t.exec( + "UPDATE repo_task_lane_ledger SET \ + executed_lane = COALESCE(?, executed_lane), \ + fallback_reason = COALESCE(?, fallback_reason), \ + session_id = COALESCE(?, session_id), updated_at = ? \ + WHERE task_id = ?", + &[ + arg_str(ex.get("lane").and_then(|v| v.as_str())), + arg_str(ex.get("fallback_reason").and_then(|v| v.as_str())), + arg_str(ex.get("session_id").and_then(|v| v.as_str())), + Arg::Text(now), + Arg::Int(task_id), + ], + )?; + } else { + t.exec( + &format!( + "INSERT INTO repo_task_lane_ledger \ + (queue, task_id, assigned_lane, executed_lane, fallback_reason, session_id, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + ), + &[ + Arg::Text(queue), + Arg::Int(task_id), + arg_str(ex.get("lane").and_then(|v| v.as_str())), + arg_str(ex.get("lane").and_then(|v| v.as_str())), + arg_str(ex.get("fallback_reason").and_then(|v| v.as_str())), + arg_str(ex.get("session_id").and_then(|v| v.as_str())), + Arg::Text(now.clone()), + Arg::Text(now), + ], + )?; + } + get_ledger(t, task_id) +} + +fn verb_with_execution( + t: &TursoBackend, + req: &Value, + row: Value, +) -> Result { + if row.is_null() { + return Ok(ok(json!({"row": Value::Null}))); + } + match record_execution(t, req, &row)? { + Some(ledger) => Ok(ok(json!({"row": row, "lane_ledger": ledger}))), + None => Ok(ok(json!({"row": row}))), + } +} + +fn req_str<'a>(req: &'a Value, key: &str) -> Option<&'a str> { + req.get(key).and_then(|v| v.as_str()) +} + +fn req_i64(req: &Value, key: &str) -> Option { + req.get(key).and_then(|v| v.as_i64()) +} + +// --------------------------------------------------------------------------- +// Verbs +// --------------------------------------------------------------------------- + +fn verb_enqueue(t: &TursoBackend, req: &Value) -> Value { + let packet = req.get("packet").cloned().unwrap_or(Value::Null); + let (errors, warnings) = validate_packet(&packet); + if !errors.is_empty() { + return json!({ + "ok": false, "exit": 2, + "error": format!("packet validation failed ({} error(s))", errors.len()), + "errors": errors, "warnings": warnings, + }); + } + let queue = req_str(req, "queue").unwrap_or("").to_string(); + let task = task_from_packet(&packet, &queue); + if req.get("dry_run").and_then(|d| d.as_bool()).unwrap_or(false) { + return ok(json!({"dry_run": true, "task": task, "warnings": warnings})); + } + let now = now_iso(); + let dedupe = task.get("dedupe_key").and_then(|v| v.as_str()).map(str::to_string); + let work = (|| -> Result { + if let Some(dk) = &dedupe { + let existing = t.query_objs( + &format!( + "SELECT {TASK_COLS} FROM tasks WHERE queue = ? AND dedupe_key = ?" + ), + &[Arg::Text(queue.clone()), Arg::Text(dk.clone())], + &TASK_JSON_COLS, + )?; + if let Some(row) = existing.into_iter().next() { + return Ok(row); + } + } + let ins = t.exec( + "INSERT INTO tasks (queue, title, body, payload, dedupe_key, priority, \ + status, not_before, max_attempts, progress, result, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, 'queued', ?, ?, '{}', '{}', ?, ?)", + &[ + Arg::Text(queue.clone()), + arg_str(task.get("title").and_then(|v| v.as_str())), + arg_str(task.get("body").and_then(|v| v.as_str())), + Arg::Text( + task.get("payload").cloned().unwrap_or(json!({})).to_string(), + ), + arg_str(dedupe.as_deref()), + task.get("priority") + .and_then(|v| v.as_i64()) + .map(Arg::Int) + .unwrap_or(Arg::Null), + arg_str(task.get("not_before").and_then(|v| v.as_str())), + task.get("max_attempts") + .and_then(|v| v.as_i64()) + .map(Arg::Int) + .unwrap_or(Arg::Int(4)), + Arg::Text(now.clone()), + Arg::Text(now), + ], + )?; + let id = ins.last_insert_rowid.unwrap_or(0); + get_task(t, id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) if !row.is_null() => ok(json!({ + "row": row, "rpc": "enqueue_repo_task_turso", "warnings": warnings + })), + Ok(_) => fail(5, "enqueue_repo_task_turso returned no row"), + 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(); + let lease_seconds = req_i64(req, "lease_seconds").unwrap_or(2700); + let lane = req_str(req, "lane").map(str::to_string); + 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("") + )); + } + } + expire_leases(t)?; + let now = now_iso(); + let lease_until = after_iso(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. + 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), \ + lane_id = ?, park_kind = NULL, wait_kind = NULL, not_before = NULL, \ + updated_at = ? \ + WHERE id = ( \ + SELECT id FROM tasks WHERE queue = ? AND ( \ + (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 <= ?)) \ + ORDER BY (priority IS NULL), priority ASC, created_at ASC LIMIT 1) \ + AND status IN ('queued', 'parked')", + &[ + Arg::Text(worker.clone()), + Arg::Text(now.clone()), + Arg::Text(lease_until.clone()), + arg_str(lane.as_deref()), + Arg::Text(now.clone()), + Arg::Text(queue.clone()), + Arg::Text(now.clone()), + Arg::Text(now.clone()), + ], + )?; + if upd.affected == 0 { + return Ok(None); + } + let rows = t.query_objs( + &format!( + "SELECT {TASK_COLS} FROM tasks \ + WHERE queue = ? AND worker_id = ? AND status = 'claimed' \ + ORDER BY claimed_at DESC LIMIT 1" + ), + &[Arg::Text(queue.clone()), Arg::Text(worker.clone())], + &TASK_JSON_COLS, + )?; + let Some(mut row) = rows.into_iter().next() else { + return Ok(None); + }; + let id = row.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + // 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()), + ], + )?; + 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", + &json!({ + "lease_seconds": lease_seconds, "via": "claim_repo_task_turso", + "cleared_session_id": cleared, "lane_id": lane, + }), + )?; + Ok(Some(row)) + })(); + match work { + Ok(Some(row)) => ok(json!({"row": row})), + Ok(None) => ok(json!({"row": Value::Null})), + Err(e) if e.starts_with("claim_repo_task:") => fail(4, e), + Err(e) => terr(e), + } +} + +fn verb_lane(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 exclusion = req_str(req, "exclusion_reason").map(str::to_string); + let work = (|| -> Result { + let Some(task) = get_task(t, task_id)? else { + return Err(format!( + "assign_repo_task_lane: task {task_id} does not exist" + )); + }; + if let Some(existing) = get_ledger(t, task_id)? { + // Idempotent (migration 0021): keep progress.lane in step. + let lane = existing + .get("assigned_lane") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let cur = task + .get("progress") + .and_then(|p| p.get("lane")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if cur != lane { + let progress = merge_obj( + &task.get("progress").cloned().unwrap_or(json!({})), + &json!({"lane": lane}), + ); + t.exec( + "UPDATE tasks SET progress = ?, updated_at = ? WHERE id = ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + } + return Ok(existing); + } + let queue = task + .get("queue") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let counts = t.query_objs( + "SELECT \ + COALESCE(SUM(CASE WHEN COALESCE(executed_lane, assigned_lane) = 'opencode' THEN 1 ELSE 0 END), 0) AS o, \ + COALESCE(SUM(CASE WHEN COALESCE(executed_lane, assigned_lane) = 'direct' THEN 1 ELSE 0 END), 0) AS d \ + FROM repo_task_lane_ledger WHERE queue = ? AND exclusion_reason IS NULL", + &[Arg::Text(queue.clone())], + &[], + )?; + let (o_count, d_count) = counts + .first() + .map(|r| { + ( + r.get("o").and_then(|v| v.as_i64()).unwrap_or(0), + r.get("d").and_then(|v| v.as_i64()).unwrap_or(0), + ) + }) + .unwrap_or((0, 0)); + let lane = if exclusion.is_some() { + "direct" + } else if o_count <= d_count { + "opencode" + } else { + "direct" + }; + let now = now_iso(); + t.exec( + "INSERT INTO repo_task_lane_ledger \ + (queue, task_id, assigned_lane, exclusion_reason, assigned_by, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, ?, ?)", + &[ + Arg::Text(queue), + Arg::Int(task_id), + Arg::Text(lane.to_string()), + arg_str(exclusion.as_deref()), + Arg::Text(worker.clone()), + Arg::Text(now.clone()), + Arg::Text(now), + ], + )?; + let progress = merge_obj( + &task.get("progress").cloned().unwrap_or(json!({})), + &json!({"lane": lane}), + ); + t.exec( + "UPDATE tasks SET progress = ?, updated_at = ? WHERE id = ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + event( + t, + Some(&worker), + Some(task_id), + "lane_assigned", + &json!({ + "assigned_lane": lane, "exclusion_reason": exclusion, + "opencode_count": o_count, "direct_count": d_count, + "via": "assign_repo_task_lane_turso", + }), + )?; + get_ledger(t, task_id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) => ok(json!({"row": row})), + Err(e) if e.starts_with("assign_repo_task_lane:") => fail(4, e), + Err(e) => terr(e), + } +} + +fn verb_bind(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 session_id = req_str(req, "session_id").unwrap_or("").to_string(); + let launched_by = req_str(req, "launched_by") + .unwrap_or("opencode-claimant") + .to_string(); + let work = (|| -> Result { + let Some(task) = get_task(t, task_id)? else { + return Err(format!( + "bind_repo_task_lane_session: task {task_id} does not exist" + )); + }; + let now = now_iso(); + let live = task.get("status").and_then(|v| v.as_str()) == Some("claimed") + && task + .get("lease_until") + .and_then(|v| v.as_str()) + .map(|l| l > now.as_str()) + .unwrap_or(false); + if !live { + return Err(format!( + "bind_repo_task_lane_session: task {task_id} is not claimed with a live lease (status {}, lease_until {})", + task.get("status").and_then(|v| v.as_str()).unwrap_or(""), + task.get("lease_until").and_then(|v| v.as_str()).unwrap_or("") + )); + } + let Some(ledger) = get_ledger(t, task_id)? else { + return Err(format!( + "bind_repo_task_lane_session: no lane ledger row for task {task_id}" + )); + }; + if let Some(existing) = ledger.get("session_id").and_then(|v| v.as_str()) { + if existing != session_id { + return Err(format!( + "bind_repo_task_lane_session: task {task_id} already bound to session {existing}" + )); + } + } + t.exec( + "UPDATE repo_task_lane_ledger SET session_id = ?, launched_by = ?, updated_at = ? \ + WHERE task_id = ?", + &[ + Arg::Text(session_id.clone()), + Arg::Text(launched_by.clone()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + let progress = merge_obj( + &task.get("progress").cloned().unwrap_or(json!({})), + &json!({"session_id": session_id, "launched_by": launched_by}), + ); + t.exec( + "UPDATE tasks SET progress = ?, updated_at = ? WHERE id = ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + event( + t, + Some(&worker), + Some(task_id), + "lane_session_bound", + &json!({ + "session_id": session_id, "launched_by": launched_by, + "via": "bind_repo_task_lane_session_turso", + }), + )?; + get_ledger(t, task_id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) => ok(json!({"row": row})), + Err(e) if e.starts_with("bind_repo_task_lane_session:") => fail(4, e), + Err(e) => terr(e), + } +} + +/// Shared guard for the claimed-by verbs: returns the task row or +/// the PG-shaped refusal. +fn claimed_by( + t: &TursoBackend, + task_id: i64, + worker: &str, + verb: &str, +) -> Result { + match get_task(t, task_id) { + Ok(Some(row)) + if row.get("status").and_then(|v| v.as_str()) == Some("claimed") + && row.get("worker_id").and_then(|v| v.as_str()) == Some(worker) => + { + Ok(row) + } + Ok(_) => Err(fail( + 5, + format!("{verb}: task {task_id} is not claimed by {worker}"), + )), + Err(e) => Err(terr(e)), + } +} + +fn verb_heartbeat(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 extend = req_i64(req, "extend_seconds").unwrap_or(900); + let row = match claimed_by(t, task_id, &worker, "heartbeat_task") { + Ok(r) => r, + Err(v) => return v, + }; + let progress = merge_obj( + &row.get("progress").cloned().unwrap_or(json!({})), + &req.get("progress").cloned().unwrap_or(json!({})), + ); + let lease_until = after_iso(extend); + let work = (|| -> Result { + t.exec( + "UPDATE tasks SET lease_until = ?, progress = ?, updated_at = ? WHERE id = ?", + &[ + Arg::Text(lease_until.clone()), + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + t.exec( + "INSERT INTO leases (task_id, worker_id, lease_until, heartbeat_at) \ + VALUES (?, ?, ?, ?) \ + ON CONFLICT(task_id) DO UPDATE SET lease_until = excluded.lease_until, \ + heartbeat_at = excluded.heartbeat_at", + &[ + Arg::Int(task_id), + Arg::Text(worker.clone()), + Arg::Text(lease_until), + Arg::Text(now_iso()), + ], + )?; + touch_worker(t, &worker, Some(task_id))?; + 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_checkpoint(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 stage = req_str(req, "stage").unwrap_or("").to_string(); + let row = match claimed_by(t, task_id, &worker, "checkpoint_task") { + Ok(r) => r, + Err(v) => return v, + }; + let given = req.get("progress").cloned().unwrap_or(json!({})); + let progress = merge_obj( + &row.get("progress").cloned().unwrap_or(json!({})), + &merge_obj(&given, &json!({"last_checkpoint": {"stage": stage, "at": now_iso()}})), + ); + let work = (|| -> Result { + t.exec( + "INSERT INTO checkpoints (task_id, worker_id, stage, progress, created_at) \ + VALUES (?, ?, ?, ?, ?)", + &[ + Arg::Int(task_id), + Arg::Text(worker.clone()), + Arg::Text(stage.clone()), + Arg::Text(given.to_string()), + Arg::Text(now_iso()), + ], + )?; + t.exec( + "UPDATE tasks SET progress = ?, updated_at = ? WHERE id = ?", + &[ + Arg::Text(progress.to_string()), + Arg::Text(now_iso()), + Arg::Int(task_id), + ], + )?; + touch_worker(t, &worker, Some(task_id))?; + event( + t, + Some(&worker), + Some(task_id), + "checkpoint", + &json!({"stage": stage, "via": "checkpoint_task_turso"}), + )?; + get_task(t, task_id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) => ok(json!({"row": row})), + Err(e) => terr(e), + } +} + +/// wait_kind mapping, copied from the PG park_task body (0023 §3). +fn wait_kind(condition: &Value) -> &'static str { + match condition.get("kind").and_then(|k| k.as_str()) { + Some("time") => "timer", + Some("ci") | Some("ci_green") | Some("pr_merged") | Some("issue_closed") + | Some("upstream_pr") => "ci", + Some("review") | Some("codex_review") | Some("pr_review") + | Some("person_answer") => "review", + Some("capacity") | Some("quota_reset") => "capacity", + _ => "external", + } +} + +fn verb_park(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(); + let row = match claimed_by(t, task_id, &worker, "park_task") { + Ok(r) => r, + Err(v) => return v, + }; + let (not_before, park_kind) = match req_str(req, "not_before") { + Some(nb) => (nb.to_string(), "absolute"), + None => ( + after_iso(req_i64(req, "delay_seconds").unwrap_or(1200)), + "relative", + ), + }; + let given_progress = req.get("progress").cloned().unwrap_or(json!({})); + let condition = req + .get("ready_condition") + .filter(|v| !v.is_null()) + .cloned() + .or_else(|| given_progress.get("ready_condition").cloned()) + .unwrap_or_else(|| json!({"kind": "time", "until": not_before})); + let wk = wait_kind(&condition); + let (progress, cleared) = clear_binding( + &row.get("progress").cloned().unwrap_or(json!({})), + "park_task", + ); + let progress = merge_obj(&progress, &given_progress); + let result = merge_obj( + &row.get("result").cloned().unwrap_or(json!({})), + &json!({"park_reason": reason}), + ); + 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), + ], + )?; + 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")?; + } + event( + t, + Some(&worker), + Some(task_id), + "parked", + &json!({ + "reason": reason, "park_kind": park_kind, "wait_kind": wk, + "not_before": not_before, "ready_condition": condition, + }), + )?; + let row = get_task(t, task_id).map(|r| r.unwrap_or(Value::Null))?; + verb_with_execution(t, req, row) + })(); + match work { + Ok(v) => v, + Err(e) => terr(e), + } +} + +fn verb_block(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_class = req_str(req, "reason_class").unwrap_or("").to_string(); + let blocker = req_str(req, "blocker").unwrap_or("").to_string(); + let row = match claimed_by(t, task_id, &worker, "block_task") { + Ok(r) => r, + Err(v) => return v, + }; + let progress = merge_obj( + &merge_obj( + &row.get("progress").cloned().unwrap_or(json!({})), + &req.get("progress").cloned().unwrap_or(json!({})), + ), + &json!({"blocker": blocker, "reason_class": reason_class}), + ); + let result = merge_obj( + &row.get("result").cloned().unwrap_or(json!({})), + &json!({"blocker": blocker, "reason_class": reason_class}), + ); + let work = (|| -> Result { + t.exec( + "UPDATE tasks SET status = 'blocked', worker_id = NULL, lease_until = NULL, \ + progress = ?, result = ?, updated_at = ? WHERE id = ?", + &[ + 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)])?; + event( + t, + Some(&worker), + Some(task_id), + "blocked", + &json!({"blocker": blocker, "reason_class": reason_class}), + )?; + 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_cancel(t: &TursoBackend, req: &Value) -> Value { + let task_id = req_i64(req, "task_id").unwrap_or(0); + let worker = req_str(req, "worker").unwrap_or("fleet-monitor").to_string(); + let reason = req_str(req, "reason").unwrap_or("").to_string(); + let work = (|| -> Result { + let Some(row) = get_task(t, task_id)? else { + return Ok(Value::Null); + }; + if ["done", "cancelled", "failed"].contains( + &row.get("status").and_then(|v| v.as_str()).unwrap_or(""), + ) { + return Ok(row); + } + let result = merge_obj( + &row.get("result").cloned().unwrap_or(json!({})), + &json!({"cancel_reason": reason}), + ); + t.exec( + "UPDATE tasks SET status = 'cancelled', worker_id = NULL, lease_until = NULL, \ + result = ?, updated_at = ? WHERE id = ?", + &[ + 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)])?; + event( + t, + Some(&worker), + Some(task_id), + "cancelled", + &json!({"reason": reason, "via": "cancel_repo_task_turso"}), + )?; + get_task(t, task_id).map(|r| r.unwrap_or(Value::Null)) + })(); + match work { + Ok(row) if !row.is_null() => ok(json!({"row": row})), + Ok(_) => fail(5, format!("cancel_repo_task: task {task_id} does not exist")), + Err(e) => terr(e), + } +} + +fn verb_fail(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 error = req_str(req, "error").unwrap_or("").to_string(); + let reason_class = req_str(req, "reason_class").unwrap_or("transient").to_string(); + let row = match claimed_by(t, task_id, &worker, "fail_repo_task") { + Ok(r) => r, + Err(v) => return v, + }; + // Migration 0023 §2, faithfully: transient + attempts left + // requeues with a backoff (900 s first, else 2700 s); 'blocked' + // blocks; anything else fails terminally. + let attempts = row.get("attempts").and_then(|v| v.as_i64()).unwrap_or(0); + let max_attempts = row.get("max_attempts").and_then(|v| v.as_i64()).unwrap_or(4); + let requeue = reason_class == "transient" && attempts < max_attempts; + let new_status = if requeue { + "queued" + } else if reason_class == "blocked" { + "blocked" + } else { + "failed" + }; + let not_before = if requeue { + after_iso(if attempts <= 1 { 900 } else { 2700 }) + } else { + row.get("not_before") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string() + }; + let progress0 = row.get("progress").cloned().unwrap_or(json!({})); + let (progress, cleared) = if requeue { + clear_binding(&progress0, "fail_repo_task") + } else { + (progress0, None) + }; + let result = merge_obj( + &row.get("result").cloned().unwrap_or(json!({})), + &json!({"reason_class": reason_class}), + ); + let work = (|| -> Result { + t.exec( + "UPDATE tasks SET status = ?, worker_id = NULL, lease_until = NULL, \ + not_before = ?, last_error = ?, progress = ?, result = ?, updated_at = ? \ + WHERE id = ?", + &[ + Arg::Text(new_status.to_string()), + Arg::Text(not_before), + Arg::Text(error.clone()), + 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 requeue { + if let Some(old) = &cleared { + on_binding_cleared(t, &worker, task_id, old, "fail_repo_task")?; + } + } + event( + t, + Some(&worker), + Some(task_id), + "failed", + &json!({ + "error": error, "reason_class": reason_class, "requeued": requeue, + "via": "fail_repo_task_turso", + }), + )?; + let row = get_task(t, task_id).map(|r| r.unwrap_or(Value::Null))?; + verb_with_execution(t, req, row) + })(); + match work { + Ok(v) => v, + Err(e) => terr(e), + } +} + +fn verb_complete(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 row = match claimed_by(t, task_id, &worker, "complete_task") { + Ok(r) => r, + Err(v) => return v, + }; + // Terminal transitions keep the session binding (migration 0023 + // header): on a done row it is the execution record. + let result = merge_obj( + &row.get("result").cloned().unwrap_or(json!({})), + &req.get("result").cloned().unwrap_or(json!({})), + ); + let work = (|| -> Result { + t.exec( + "UPDATE tasks SET status = 'done', lease_until = NULL, result = ?, \ + updated_at = ? WHERE id = ?", + &[ + 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)])?; + touch_worker(t, &worker, None)?; + event( + t, + Some(&worker), + Some(task_id), + "completed", + &json!({"via": "complete_task_turso"}), + )?; + let row = get_task(t, task_id).map(|r| r.unwrap_or(Value::Null))?; + verb_with_execution(t, req, row) + })(); + match work { + Ok(v) => v, + Err(e) => terr(e), + } +} + +fn verb_list(t: &TursoBackend, req: &Value) -> Value { + let queue = req_str(req, "queue").unwrap_or("").to_string(); + let limit = match crate::client::list_limit_or_default(req_i64(req, "limit")) { + Ok(l) => l, + Err(e) => return fail(2, e), + }; + let rich = req.get("rich").and_then(|r| r.as_bool()).unwrap_or(false); + let select = if rich { + "id, queue, title, priority, status, dedupe_key, created_at, not_before, \ + worker_id, lease_until, lane_id, attempts, max_attempts, progress" + } else { + "id, queue, title, priority, status, dedupe_key, created_at, not_before" + }; + let mut sql = format!( + "SELECT {select} FROM tasks WHERE queue = ?" + ); + let mut args: Vec = vec![Arg::Text(queue)]; + if let Some(s) = req_str(req, "status") { + sql += " AND status = ?"; + args.push(Arg::Text(s.to_string())); + } + if let Some(nb) = req_str(req, "not_before") { + sql += " AND (not_before IS NULL OR not_before <= ?)"; + args.push(Arg::Text(nb.to_string())); + } + sql += &format!( + " ORDER BY (priority IS NULL), priority ASC, created_at ASC LIMIT {limit}" + ); + let json_cols: &[&str] = if rich { &["progress"] } else { &[] }; + match t.query_objs(&sql, &args, json_cols) { + Ok(rows) => ok(json!({"rows": rows})), + Err(e) => terr(e), + } +} + +fn verb_health(t: &TursoBackend, req: &Value) -> Value { + let queue_filter = req_str(req, "queue").map(str::to_string); + let work = (|| -> Result { + let mut sql = "SELECT queue, status, COUNT(*) AS n, \ + MIN(CASE WHEN status = 'queued' THEN created_at END) AS oldest_queued_at \ + FROM tasks" + .to_string(); + let mut args: Vec = Vec::new(); + if let Some(q) = &queue_filter { + sql += " WHERE queue = ?"; + args.push(Arg::Text(q.clone())); + } + sql += " GROUP BY queue, status ORDER BY queue, status"; + let rows = t.query_objs(&sql, &args, &[])?; + let mut by_queue: Map = Map::new(); + for r in &rows { + let q = r + .get("queue") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let entry = by_queue.entry(q.clone()).or_insert_with(|| { + json!({ + "queue": q, "queued": 0, "claimed": 0, "parked": 0, + "blocked": 0, "done": 0, "cancelled": 0, "failed": 0, + "total": 0, "oldest_queued_at": Value::Null, + }) + }); + let status = r + .get("status") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + let n = r.get("n").and_then(|v| v.as_i64()).unwrap_or(0); + if let Some(obj) = entry.as_object_mut() { + if let Some(slot) = obj.get_mut(&status) { + *slot = json!(n); + } + let total = obj.get("total").and_then(|v| v.as_i64()).unwrap_or(0); + obj.insert("total".to_string(), json!(total + n)); + if status == "queued" { + obj.insert( + "oldest_queued_at".to_string(), + r.get("oldest_queued_at").cloned().unwrap_or(Value::Null), + ); + } + } + } + Ok(Value::Array(by_queue.into_iter().map(|(_, v)| v).collect())) + })(); + match work { + Ok(rows) => { + let netloc = t + .url() + .split("://") + .nth(1) + .unwrap_or(t.url()) + .split('/') + .next() + .unwrap_or("") + .to_string(); + ok(json!({ + "project_netloc": netloc, + "project_source": "turso", + "backend": "turso", + "rows": rows, + })) + } + Err(e) => terr(e), + } +} + +fn verb_signal_count(t: &TursoBackend, req: &Value) -> Value { + let queue = req_str(req, "queue").unwrap_or("").to_string(); + let work = (|| -> Result { + let rows = t.query_objs( + "SELECT COUNT(*) AS n, MIN(created_at) AS oldest FROM tasks \ + WHERE queue = ? AND status = 'queued'", + &[Arg::Text(queue)], + &[], + )?; + let first = rows.into_iter().next().unwrap_or(json!({})); + Ok(json!({ + "queued_count": first.get("n").cloned().unwrap_or(json!(0)), + "oldest_queued_at": first.get("oldest").cloned().unwrap_or(Value::Null), + })) + })(); + match work { + Ok(v) => { + let mut m = json!({"ok": true}); + if let (Some(dst), Some(src)) = (m.as_object_mut(), v.as_object()) { + for (k, val) in src { + dst.insert(k.clone(), val.clone()); + } + } + m + } + Err(e) => terr(e), + } +} + +/// The Turso backend's half of the broker dispatch: every verb the +/// Postgres path serves except /validate (purely local) and +/// /healthz (transport-level), which stay in queue_broker::dispatch. +pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { + match path { + "/enqueue" => verb_enqueue(t, req), + "/claim" => verb_claim(t, req), + "/lane" => verb_lane(t, req), + "/bind" => verb_bind(t, req), + "/heartbeat" => verb_heartbeat(t, req), + "/checkpoint" => verb_checkpoint(t, req), + "/park" => verb_park(t, req), + "/block" => verb_block(t, req), + "/cancel" => verb_cancel(t, req), + "/fail" => verb_fail(t, req), + "/complete" => verb_complete(t, req), + "/list" => verb_list(t, req), + "/health" => verb_health(t, req), + "/signal-count" => verb_signal_count(t, req), + _ => fail(2, format!("unknown command {path}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn iso_epoch_and_known_instants() { + assert_eq!(iso(0), "1970-01-01T00:00:00Z"); + // 2026-11-07T03:00:00Z == 1794020400 (the night this landed). + assert_eq!(iso(1_794_020_400), "2026-11-07T03:00:00Z"); + assert_eq!(iso(1_794_020_400 + 2700), "2026-11-07T03:45:00Z"); + } + + #[test] + fn iso_strings_sort_chronologically() { + let mut v: Vec = [100_000, 0, 1_794_020_400, 86_400, 999_999_999] + .iter() + .map(|n| iso(*n)) + .collect(); + let mut sorted = v.clone(); + sorted.sort(); + v.sort_by_key(|s| s.clone()); + assert_eq!(v, sorted); + let mut by_str = vec![iso(200), iso(100), iso(300)]; + by_str.sort(); + assert_eq!(by_str, vec![iso(100), iso(200), iso(300)]); + } + + #[test] + fn wait_kind_mapping_matches_pg_park() { + assert_eq!(wait_kind(&json!({"kind": "time"})), "timer"); + assert_eq!(wait_kind(&json!({"kind": "pr_merged"})), "ci"); + assert_eq!(wait_kind(&json!({"kind": "person_answer"})), "review"); + assert_eq!(wait_kind(&json!({"kind": "quota_reset"})), "capacity"); + assert_eq!(wait_kind(&json!({"kind": "something_else"})), "external"); + assert_eq!(wait_kind(&json!({})), "external"); + } + + #[test] + fn clear_binding_stamps_and_strips() { + let p = json!({"session_id": "s1", "launched_by": "x", "keep": 1}); + let (out, cleared) = clear_binding(&p, "expire_leases"); + assert_eq!(cleared.as_deref(), Some("s1")); + assert!(out.get("session_id").is_none()); + assert!(out.get("launched_by").is_none()); + assert_eq!(out.get("keep"), Some(&json!(1))); + assert_eq!( + out.get("session_cleared").and_then(|c| c.get("via")), + Some(&json!("expire_leases")) + ); + let (out2, cleared2) = clear_binding(&json!({"keep": 1}), "x"); + assert!(cleared2.is_none()); + assert_eq!(out2, json!({"keep": 1})); + } + + #[test] + fn merge_obj_is_shallow_and_object_only() { + let out = merge_obj(&json!({"a": 1, "b": 2}), &json!({"b": 3, "c": 4})); + assert_eq!(out, json!({"a": 1, "b": 3, "c": 4})); + assert_eq!(merge_obj(&json!(null), &json!({"a": 1})), json!({"a": 1})); + } +} From 0d66f51d083c56f28c8819f97223c0100124d909 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 21:54:35 -0600 Subject: [PATCH 2/4] runbook: decommission-only end state, backup load step, simplified post-cutover backfill (#6741) Drew data plan 2026-11-06 21:49-21:52 CST: muse-dev2 is decommissioned (left in place, unused), never deleted; the Turso queue is populated from the last R2 backup as-is (sanity readback only) with in-flight claims handled by normal lease-expiry; cutover is GO on build+load verification and does not wait for Postgres; the backup-to-crash gap is a manual backfill afterwards (Postgres wins on conflict); the action outbox drains separately against the GitHub fallback. --- doc/fleet/queue-turso-cutover.md | 102 +++++++++++++++++++------------ 1 file changed, 64 insertions(+), 38 deletions(-) diff --git a/doc/fleet/queue-turso-cutover.md b/doc/fleet/queue-turso-cutover.md index b41eff82e3..75c5ff0e8e 100644 --- a/doc/fleet/queue-turso-cutover.md +++ b/doc/fleet/queue-turso-cutover.md @@ -1,8 +1,9 @@ # Queue core on Turso — cutover runbook (#6741) -**Status:** backend BUILT and PROVEN live 2026-11-06; production -broker still on Postgres (default unchanged). Cutover = the env -flip in step 2 below, executed as its own change. +**Status:** backend BUILT and PROVEN live 2026-11-06. Cutover is +GO as soon as the backup load (§ Cutover step 2) verifies — Drew, +2026-11-06 21:52 CST; it does NOT wait for the Postgres backfill, +which is a later manual follow-up (§ After cutover). **Why:** the queue core (`agent.tasks`, `leases`, `lanes`, `workers`, `checkpoints`, `repo_task_lane_ledger`) was the one @@ -73,36 +74,57 @@ Against the real `muse-queue` DB, through the real client verbs: Verify the installed binary answers `fleet queue health` against a Turso-backed test broker on a side port (as in the proof) before touching the production broker. -2. **Flip:** set `QUEUE_BROKER_BACKEND=turso` in the queue-broker - unit env on the laptop and restart the unit. Nothing else - changes: clients, claimant, and worker runbooks already speak - only to the broker. **Drain decision first:** the Turso queue - starts empty. Either (a) flip while the GitHub fallback is - carrying work (PG is down anyway — there is nothing to drain - until PG returns), or (b) if PG has returned, let PG claims - drain to zero, export any open queued/parked/blocked PG tasks, - and re-enqueue them into Turso preserving dedupe keys. Option - (a) is the expected path while #6619 is open. -3. **Verify:** `fleet queue health` names the Turso host; run one - labeled proof cycle (the #6741 packet shape) on the production - broker; watch the first real lane claims land in the Turso - `events` table. -4. **Soak:** GitHub fallback mode stays ACTIVE as the bridge +2. **Backup load:** populate `muse-queue` from the fleet's last + DIY R2 backup of muse-dev2 (prefix `pg/muse-dev2`, agent + schema; the restored export's location, row counts, and + coverage timestamp are recorded on #6619). Copy the queue-core + tables (`tasks`, `leases`, `workers`, `checkpoints`, + `repo_task_lane_ledger`) in as-is — no row-perfect verification + (Drew, 2026-11-06 21:51 CST); a sanity count readback against + the backup record is the check. The queue therefore comes up + holding real state as of the backup, not empty. **In-flight + claims in the restored data:** their `lease_until` values are + in the past by cutover time, so the queue's normal lease-expiry + semantics handle them — the first claims against the Turso + broker run `expire_leases`, returning those rows to `queued` + with their bindings cleared; no worker from the backup era + holds anything live. (The two labeled #6741 proof tasks, + ids 1–2, are also in the table — both `done`.) +3. **Flip:** add a systemd drop-in for `queue-broker.service` + (the fastlane pattern): `Environment=QUEUE_BROKER_BACKEND=turso` + and `ExecStart` repointed at the step-1 build; daemon-reload; + restart the unit. Nothing else changes: clients, claimant, and + worker runbooks already speak only to the broker. The broker + resolves the Turso token from the secrets broker by name + (`turso.muse-queue-rw-token`) — no token file in the unit. +4. **Verify:** `fleet queue health` names the Turso host and shows + the restored queues; run one labeled proof cycle (the #6741 + packet shape) through the production broker; watch the first + real lane claims land in the Turso `events` table. +5. **Soak:** GitHub fallback mode stays ACTIVE as the bridge until the Turso broker has carried a full day of real claims; workers keep routing to fallback whenever `fleet queue health` fails, per runbook §0a. -## Interaction with the PG staged-recovery sequence - -**Unaffected.** If Postgres returns before cutover, the staged -sequence still runs in its order — outbox reconciliation (17) → -monitor requeue (16) → 142-at-cap requeue → migration finalize -scripts (`migrate_slice6_mirror.py`, then `finalize_pg.py`). The -requeues target the PG queue; if the flip (step 2) has already -happened when PG returns, run the export half of the finalize -scripts and the mirror drops, but skip the requeues — the work -they would revive is re-enqueued into Turso per step 2(b) or has -already been carried by the fallback. +## After cutover: the Postgres backfill (manual, unscheduled) + +The gap between the backup's coverage point and the crash +(data plane down 2026-11-06 19:25Z) is **not** a cutover gate. +Whenever the Postgres data plane becomes available again, one +manual step ports the missing changes into Turso: tasks created, +completed, or transitioned in the gap, identified by comparing +PG `agent.tasks` (and its ledger) against the Turso tables by +dedupe key / task identity. **If the two sources conflict on a +task, Postgres (the later state) wins.** The action outbox is +drained separately, against the GitHub fallback, by its own lane +— it is no longer part of this sequence — and the earlier staged +monitor (16) / 142-at-cap requeues are superseded: their work is +carried by the fallback or re-derived from GitHub issues. The +migration finalize scripts (`migrate_slice6_mirror.py`, +`finalize_pg.py`) remain PG-side hygiene for decommission time, +unrelated to the queue. After the backfill, muse-dev2 is +**decommissioned: left in place, unused — never deleted** +(Drew's data plan, 2026-11-06 21:49 CST). ## Rollback @@ -157,8 +179,11 @@ the rollback complete. ## What still touches Postgres after the queue cutover -The delete-the-project checklist. Nothing below was moved or -dropped by #6741. +The decommission checklist. Per Drew's data plan (2026-11-06), +muse-dev2 is **decommissioned — left in place, unused — never +deleted**; every item below is a move-or-retire decision that +stands between here and that decommission, and nothing below was +moved or dropped by #6741. - **agent.events (PG stream, ~196k rows, FK → tasks)** — its queue-transition writers are replaced by the Turso `events` @@ -168,9 +193,10 @@ dropped by #6741. export-or-abandon per the #5690 append-stream class. - **pg_cron jobs** (`agent-expire-leases` every minute, `agent-prune-events` daily, `park-revalidation-daily`) — they - die with the project. Expire is covered inside claim; prune - (30-day retention) and park revalidation need small ports to a - broker-side periodic task (deviations 4–5). + live inside the project and become irrelevant at decommission + (expire is covered inside claim); prune (30-day retention) and + park revalidation need small ports to a broker-side periodic + task (deviations 4–5). - **ci.events + the `github-ci` Edge Function** — the writer runs ON Supabase (Edge Functions), upserts PG, and dual-writes Turso `ci_events` (live since 2026-11-06). The morning-readout reader @@ -189,8 +215,8 @@ dropped by #6741. ainventory relational core (`models`, `measurement_events`, `price_events`, `provider_policies`, `benchmark_results` + the views over them) is KEEP-on-Postgres BY DESIGN — not a leftover; - deleting the project needs a deliberate re-home decision for - that core. + full decommission waits on a deliberate re-home decision for + that core (until then the project stays partially live for it). - **Slice-1 `sources` remainder (#5695)** — 5 rows exist only in PG (`automation`/`finance`/`home`/`research` sources; D1 `muse-config` holds the other 49 of 54). Moving takes one PG @@ -215,5 +241,5 @@ dropped by #6741. vault 1 — the 41-table RETIRE class)** — no fleet consumer was found in the audits; the only platform dependency is Edge Functions hosting (the `github-ci` receiver above). Re-home - that function first; nothing else needs moving, and deleting - the project is what retires these. + that function first; nothing else needs moving — these stay + in the decommissioned project, unused, like everything else. From 48a5855d5fdab5913172558058fe4f6abd898040 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 22:11:33 -0600 Subject: [PATCH 3/4] fleet-queue: PG-true schema corrections, no-double-serve guard, permanent fallback switch (#6741) Schema corrections from the real backup export (code#6619 comment 6701907139): workers is the PG roster shape, checkpoints is a per-worker KV, the lane ledger carries assigned_at/executed_at (launched_by lives in tasks.progress), tasks gains completed_at, and the dedupe index is NOT unique (PG data itself carries duplicate dedupe pairs). Guard (Drew master plan 2026-11-06): a primary-store claim whose issue is live/contested in the GitHub fallback under another worker is auto-blocked (reason_class fallback_held) and reported as no-claim, so the Turso queue never double-serves a fallback-held issue; the check fails open with a guard_warning when GitHub is unreachable. Permanent fallback arming: claim/heartbeat/checkpoint/complete/health now route ANY primary-store failure (transport or error envelope) to a machine-readable fallback switch (stdout JSON with fallback:true, exit 6) instead of dying; REPO_QUEUE_NO_FALLBACK_SWITCH=1 restores die-on-error. --- pkgs/fleet/crates/fleet-queue/src/client.rs | 297 ++++++++++++++++-- pkgs/fleet/crates/fleet-queue/src/fallback.rs | 15 + .../crates/fleet-queue/src/turso_queue.rs | 79 +++-- 3 files changed, 337 insertions(+), 54 deletions(-) diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index 138e432d1f..4dbac2186b 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -267,7 +267,7 @@ fn spawn_broker() { /// POST one queue-broker command; dies (exit 3) when the broker path /// is unavailable, otherwise returns the response envelope (which may /// itself be {ok:false, exit, error} — the caller decides). -fn call(path: &str, body: &Value) -> Value { +fn call_result(path: &str, body: &Value) -> Result { // #6450 posture (crate::backoff — the one shared policy): a // broker envelope carrying a 57014 / PGRST002-class error is // retried with exponential backoff + jitter instead of dying on @@ -288,11 +288,89 @@ fn call(path: &str, body: &Value) -> Value { attempt += 1; continue; } - return v; + return Ok(v); } - Err(e) => die(3, &e), + Err(e) => return Err((3, e)), + } + } +} + +fn call(path: &str, body: &Value) -> Value { + match call_result(path, body) { + Ok(v) => v, + Err((code, msg)) => die(code, &msg), + } +} + +// --------------------------------------------------------------------------- +// Permanent fallback arming (#6741; Drew's master plan, 2026-11-06: +// "encounter any issue -> fallback"). The GitHub fallback is not an +// outage-only mode any more: for the work verbs (claim, heartbeat, +// checkpoint, complete, health), ANY primary-store failure — broker +// unreachable, or an error envelope from the broker — switches the +// caller to the GitHub fallback for that work instead of dying. +// The switch is machine-readable: one JSON object on stdout with +// "fallback": true, and exit code FALLBACK_SWITCH_EXIT, so a worker +// loop can branch on it without parsing prose. Set +// REPO_QUEUE_NO_FALLBACK_SWITCH=1 to restore the plain die-on-error +// behavior (operator escape hatch). +// --------------------------------------------------------------------------- + +const FALLBACK_SWITCH_EXIT: i32 = 6; + +fn fallback_switch_enabled() -> bool { + std::env::var("REPO_QUEUE_NO_FALLBACK_SWITCH") + .map(|v| v != "1") + .unwrap_or(true) +} + +fn fallback_switch_json(verb: &str, code: i32, msg: &str) -> Value { + json!({ + "ok": false, + "fallback": true, + "switch_to": "github-fallback", + "verb": verb, + "broker_exit": code, + "error": msg, + "hint": "continue this work with: fleet queue fallback scan|claim|heartbeat|release", + }) +} + +fn fallback_switch(verb: &str, code: i32, msg: &str) -> ! { + eprint(&format!( + "repo-queue: primary queue store failed on {verb} (exit {code}): {msg}; switching this work to the GitHub fallback" + )); + print_json(&fallback_switch_json(verb, code, msg)); + exit(FALLBACK_SWITCH_EXIT); +} + +fn call_fb(path: &str, body: &Value) -> Value { + match call_result(path, body) { + Ok(v) => v, + Err((code, msg)) => { + if fallback_switch_enabled() { + fallback_switch(path, code, &msg) + } else { + die(code, &msg) + } + } + } +} + +fn unwrap_ok_fb(resp: Value, verb: &str) -> Value { + if resp.get("ok").and_then(|o| o.as_bool()) == Some(false) { + let code = resp.get("exit").and_then(|e| e.as_i64()).unwrap_or(4) as i32; + let msg = resp + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("queue-broker error") + .to_string(); + if fallback_switch_enabled() { + fallback_switch(verb, code, &msg); } + die(code, &msg); } + resp } /// Unwrap an envelope: on {ok:false} print the error and exit with its @@ -971,21 +1049,136 @@ fn cmd_list(rest: &[String]) -> i32 { fn cmd_claim(rest: &[String]) -> i32 { let args = parse_args(rest, &["queue", "worker", "lease-seconds", "lane"], &[]); reject_extra_pos("claim", &args, 0); + let worker = opt_worker(&args); let mut body = json!({ "queue": opt_queue(&args), - "worker": opt_worker(&args), + "worker": worker, "lease_seconds": args.get_i64("lease-seconds").unwrap_or(2700), }); if let Some(lane) = args.get("lane") { body["lane"] = json!(lane); } - let resp = unwrap_ok(call("/claim", &body)); - let (out, code) = claim_output(&resp); + let resp = unwrap_ok_fb(call_fb("/claim", &body), "/claim"); + let (mut out, code) = claim_output(&resp); if code != 0 { eprint("repo-queue: no claimable task"); + print_json(&out); + return code; + } + // No-double-serve guard (#6741): a task whose issue is held in + // the GitHub fallback right now must not be served from the + // primary store — block it back and report no claim. + match fallback_guard(&out, &worker) { + GuardOutcome::HeldBy(holder) => { + let task_id = out.get("id").and_then(|v| v.as_i64()).unwrap_or(0); + let (repo, issue) = task_issue(&out); + 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", + ); + } + print_json(&json!({ + "task": Value::Null, + "guard": "fallback_held", + "held_by": holder, + "repo": repo, + "issue": issue, + })); + NO_CLAIM_EXIT + } + GuardOutcome::Unchecked(e) => { + if let Some(o) = out.as_object_mut() { + o.insert( + "guard_warning".to_string(), + json!(format!( + "fallback double-serve guard could not check GitHub: {e}" + )), + ); + } + print_json(&out); + code + } + GuardOutcome::Serve => { + print_json(&out); + code + } + } +} + +/// The (repo, issue) identity a claimed task's payload carries, for +/// the fallback guard. ("", 0) when the packet names none. +fn task_issue(row: &Value) -> (String, i64) { + let payload = row.get("payload").cloned().unwrap_or(Value::Null); + ( + payload + .get("repo") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + payload + .get("issue") + .and_then(|i| i.get("number")) + .and_then(|n| n.as_i64()) + .unwrap_or(0), + ) +} + +#[derive(Debug, PartialEq, Eq)] +enum GuardDecision { + Serve, + HeldBy(String), +} + +/// Pure guard decision over a fallback claim-state object (the +/// shape `fallback status` prints): live or contested in the +/// fallback under a DIFFERENT worker means hands off; anything +/// else (free / released / stale / held by me) may be served. +fn guard_decision(state: &Value, my_worker: &str) -> GuardDecision { + let name = state.get("state").and_then(|v| v.as_str()).unwrap_or(""); + let holder = state.get("worker").and_then(|v| v.as_str()).unwrap_or(""); + if (name == "live" || name == "contested") && !holder.is_empty() && holder != my_worker { + GuardDecision::HeldBy(holder.to_string()) + } else { + GuardDecision::Serve + } +} + +enum GuardOutcome { + Serve, + HeldBy(String), + /// The GitHub check itself failed: serve, but say so — the + /// guard fails open with a warning rather than stalling every + /// claim on a GitHub outage (the primary store failing is what + /// the fallback switch above is for). + Unchecked(String), +} + +fn fallback_guard(row: &Value, my_worker: &str) -> GuardOutcome { + let (repo, issue) = task_issue(row); + if repo.is_empty() || issue <= 0 { + return GuardOutcome::Serve; + } + match crate::fallback::issue_claim_state(&repo, issue) { + Ok(state) => match guard_decision(&state, my_worker) { + GuardDecision::HeldBy(h) => GuardOutcome::HeldBy(h), + GuardDecision::Serve => GuardOutcome::Serve, + }, + Err(e) => GuardOutcome::Unchecked(e), } - print_json(&out); - code } /// Exit code for a claim that found no task: nonzero, so an empty @@ -1051,15 +1244,18 @@ fn cmd_heartbeat(rest: &[String]) -> i32 { &[], ); reject_extra_pos("heartbeat", &args, 1); - let resp = unwrap_ok(call( + let resp = unwrap_ok_fb( + call_fb( + "/heartbeat", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "extend_seconds": args.get_i64("extend-seconds").unwrap_or(900), + "progress": progress_arg(&args), + }), + ), "/heartbeat", - &json!({ - "task_id": args.pos_i64(0, "task_id"), - "worker": opt_worker(&args), - "extend_seconds": args.get_i64("extend-seconds").unwrap_or(900), - "progress": progress_arg(&args), - }), - )); + ); print_json(&require_row(&resp, "heartbeat_task")); 0 } @@ -1070,15 +1266,18 @@ fn cmd_checkpoint(rest: &[String]) -> i32 { let stage = args .get("stage") .unwrap_or_else(|| die(2, "checkpoint: --stage is required")); - let resp = unwrap_ok(call( + let resp = unwrap_ok_fb( + call_fb( + "/checkpoint", + &json!({ + "task_id": args.pos_i64(0, "task_id"), + "worker": opt_worker(&args), + "stage": stage, + "progress": progress_arg(&args).unwrap_or(json!({})), + }), + ), "/checkpoint", - &json!({ - "task_id": args.pos_i64(0, "task_id"), - "worker": opt_worker(&args), - "stage": stage, - "progress": progress_arg(&args).unwrap_or(json!({})), - }), - )); + ); print_json(&require_row(&resp, "checkpoint_task")); 0 } @@ -1320,7 +1519,7 @@ fn cmd_complete(rest: &[String]) -> i32 { if let Some(ex) = ex { body["execution"] = ex; } - let resp = unwrap_ok(call("/complete", &body)); + let resp = unwrap_ok_fb(call_fb("/complete", &body), "/complete"); row_or_ledger(&resp, "complete_task"); 0 } @@ -1332,7 +1531,7 @@ fn cmd_health(rest: &[String]) -> i32 { if let Some(q) = args.get("queue") { body["queue"] = json!(q); } - let resp = unwrap_ok(call("/health", &body)); + let resp = unwrap_ok_fb(call_fb("/health", &body), "/health"); let netloc = resp .get("project_netloc") .and_then(|v| v.as_str()) @@ -1466,6 +1665,52 @@ mod tests { use super::*; use proptest::prelude::*; + #[test] + fn fallback_switch_json_shape() { + let v = fallback_switch_json("/claim", 4, "store down"); + assert_eq!(v["ok"], json!(false)); + assert_eq!(v["fallback"], json!(true)); + assert_eq!(v["switch_to"], json!("github-fallback")); + assert_eq!(v["verb"], json!("/claim")); + assert_eq!(v["broker_exit"], json!(4)); + assert_eq!(FALLBACK_SWITCH_EXIT, 6); + } + + #[test] + fn guard_decision_holds_only_live_or_contested_others() { + let live_other = json!({"state": "live", "worker": "lane-b"}); + assert_eq!( + guard_decision(&live_other, "lane-a"), + GuardDecision::HeldBy("lane-b".to_string()) + ); + let contested = json!({"state": "contested", "worker": "lane-b"}); + assert_eq!( + guard_decision(&contested, "lane-a"), + GuardDecision::HeldBy("lane-b".to_string()) + ); + // Held by me, stale, released, free: all servable. + assert_eq!(guard_decision(&live_other, "lane-b"), GuardDecision::Serve); + assert_eq!( + guard_decision(&json!({"state": "stale", "worker": "lane-b"}), "lane-a"), + GuardDecision::Serve + ); + assert_eq!( + guard_decision(&json!({"state": "released", "worker": "lane-b"}), "lane-a"), + GuardDecision::Serve + ); + assert_eq!( + guard_decision(&json!({"state": "free"}), "lane-a"), + GuardDecision::Serve + ); + } + + #[test] + fn task_issue_reads_payload_identity() { + let row = json!({"payload": {"repo": "developing-today/code", "issue": {"number": 6741}}}); + assert_eq!(task_issue(&row), ("developing-today/code".to_string(), 6741)); + assert_eq!(task_issue(&json!({"payload": {}})), (String::new(), 0)); + } + fn pos(list: &[&str]) -> Vec { list.iter().map(|s| s.to_string()).collect() } diff --git a/pkgs/fleet/crates/fleet-queue/src/fallback.rs b/pkgs/fleet/crates/fleet-queue/src/fallback.rs index afaa58bece..35875545ed 100644 --- a/pkgs/fleet/crates/fleet-queue/src/fallback.rs +++ b/pkgs/fleet/crates/fleet-queue/src/fallback.rs @@ -1118,6 +1118,21 @@ fn cmd_release(rest: &[String]) -> i32 { 0 } +/// Programmatic claim-state lookup (#6741): the GitHub-fallback +/// claim state of one issue, for the queue client's +/// no-double-serve guard. Same marker fold and lease as +/// `fallback status` (default 30 min, FLEET_QUEUE_FALLBACK_LEASE_MIN +/// override), minus the CLI surface. +pub fn issue_claim_state(repo: &str, number: i64) -> Result { + let markers = fetch_markers(repo, number)?; + let lease_min = std::env::var("FLEET_QUEUE_FALLBACK_LEASE_MIN") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .filter(|m| *m >= 1) + .unwrap_or(DEFAULT_LEASE_MIN); + Ok(fold_claim(&markers, now_epoch(), lease_min * 60).to_json()) +} + pub fn run(args: &[String]) -> i32 { if args.is_empty() { eprintln!("usage: repo-queue fallback ..."); diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 3feee17594..161bfbda71 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -49,10 +49,10 @@ pub const TURSO_TOKEN_SECRET_NAME: &str = "turso.muse-queue-rw-token"; const TASK_COLS: &str = "id, queue, title, body, payload, dedupe_key, priority, status, \ not_before, worker_id, claimed_at, lease_until, lane_id, attempts, max_attempts, \ progress, result, last_error, park_kind, wait_kind, ready_condition, \ - last_checked_at, check_outcome, created_at, updated_at"; + last_checked_at, check_outcome, created_at, updated_at, completed_at"; const LEDGER_COLS: &str = "id, queue, task_id, assigned_lane, executed_lane, \ - exclusion_reason, assigned_by, session_id, launched_by, fallback_reason, \ - created_at, updated_at"; + exclusion_reason, assigned_by, session_id, fallback_reason, \ + assigned_at, executed_at, updated_at"; /// Task columns whose stored TEXT is JSON (PG jsonb) — parsed back /// into values so the wire shape matches the Postgres broker's. const TASK_JSON_COLS: [&str; 4] = ["payload", "progress", "result", "ready_condition"]; @@ -366,8 +366,12 @@ const SCHEMA: [&str; 10] = [ progress TEXT NOT NULL DEFAULT '{}', result TEXT NOT NULL DEFAULT '{}', \ last_error TEXT, park_kind TEXT, wait_kind TEXT, ready_condition TEXT, \ last_checked_at TEXT, check_outcome TEXT, \ - created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", - "CREATE UNIQUE INDEX IF NOT EXISTS tasks_queue_dedupe \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, \ + completed_at TEXT)", + // NOT unique: the PG data itself carries duplicate (queue, dedupe_key) + // pairs from before dedupe was enforced, and the backup load must + // accept them as-is; enqueue dedupe is a read-then-insert check. + "CREATE INDEX IF NOT EXISTS tasks_queue_dedupe \ ON tasks(queue, dedupe_key) WHERE dedupe_key IS NOT NULL", "CREATE INDEX IF NOT EXISTS tasks_claim_scan \ ON tasks(queue, status, priority, created_at)", @@ -378,18 +382,19 @@ const SCHEMA: [&str; 10] = [ lane_id TEXT PRIMARY KEY, worker_id TEXT NOT NULL, \ queue TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1)", "CREATE TABLE IF NOT EXISTS workers (\ - worker_id TEXT PRIMARY KEY, last_seen_at TEXT NOT NULL, \ - current_task_id INTEGER)", + worker_id TEXT PRIMARY KEY, role TEXT NOT NULL DEFAULT '', \ + display_name TEXT, status TEXT NOT NULL DEFAULT 'idle', \ + last_heartbeat_at TEXT, created_at TEXT)", "CREATE TABLE IF NOT EXISTS checkpoints (\ - id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER NOT NULL, \ - worker_id TEXT NOT NULL, stage TEXT NOT NULL, \ - progress TEXT NOT NULL DEFAULT '{}', created_at TEXT NOT NULL)", + worker_id TEXT NOT NULL, key TEXT NOT NULL, \ + value TEXT NOT NULL DEFAULT '{}', updated_at TEXT NOT NULL, \ + PRIMARY KEY (worker_id, key))", "CREATE TABLE IF NOT EXISTS repo_task_lane_ledger (\ id INTEGER PRIMARY KEY AUTOINCREMENT, queue TEXT NOT NULL, \ task_id INTEGER NOT NULL UNIQUE, assigned_lane TEXT, executed_lane TEXT, \ exclusion_reason TEXT, assigned_by TEXT, session_id TEXT, \ - launched_by TEXT, fallback_reason TEXT, \ - created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", + fallback_reason TEXT, assigned_at TEXT, executed_at TEXT, \ + updated_at TEXT NOT NULL)", "CREATE TABLE IF NOT EXISTS events (\ id INTEGER PRIMARY KEY AUTOINCREMENT, worker_id TEXT, task_id INTEGER, \ kind TEXT NOT NULL, detail TEXT NOT NULL DEFAULT '{}', \ @@ -479,14 +484,22 @@ fn event( } fn touch_worker(t: &TursoBackend, worker: &str, task_id: Option) -> Result<(), TErr> { + // PG workers is the roster table (id/role/display_name/status/ + // last_heartbeat_at): a touch upserts the heartbeat and marks + // the worker working while it holds a task, idle when it + // releases one. Unknown workers enter with an empty role. + let status = if task_id.is_some() { "working" } else { "idle" }; t.exec( - "INSERT INTO workers (worker_id, last_seen_at, current_task_id) VALUES (?, ?, ?) \ - ON CONFLICT(worker_id) DO UPDATE SET last_seen_at = excluded.last_seen_at, \ - current_task_id = COALESCE(excluded.current_task_id, workers.current_task_id)", + "INSERT INTO workers (worker_id, role, status, last_heartbeat_at, created_at) \ + VALUES (?, '', ?, ?, ?) \ + ON CONFLICT(worker_id) DO UPDATE SET \ + last_heartbeat_at = excluded.last_heartbeat_at, \ + status = excluded.status", &[ Arg::Text(worker.to_string()), + Arg::Text(status.to_string()), + Arg::Text(now_iso()), Arg::Text(now_iso()), - task_id.map(Arg::Int).unwrap_or(Arg::Null), ], )?; Ok(()) @@ -611,12 +624,14 @@ fn record_execution(t: &TursoBackend, req: &Value, row: &Value) -> Result