Skip to content

fleet-queue: Turso backend for the queue core (muse-queue) (#6741) - #6755

Merged
dezren39 merged 4 commits into
mainfrom
queue/6741-turso-backend
Nov 7, 2026
Merged

dezren39 merged 4 commits into
mainfrom
queue/6741-turso-backend

Conversation

@dezren39

@dezren39 dezren39 commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Closes the queue-core gap in the Turso migration: the dedicated replacement Drew ordered 2026-11-06 21:34 CST.

Database: Turso muse-queue stood up (org dezren39, group great-star-lord, id 01a1b414-2d01-7c27-8a43-783bb5b09296); rw token in BWS turso.muse-queue-rw-token, verified by live readback.

Code: fleet-queue gains a Turso backend behind the existing broker protocol — QUEUE_BROKER_BACKEND=turso selects it; Postgres remains the default, no client changes, no production flip in this PR. Semantics reconstructed from the recovered PG function bodies (claimant migrations 0021–0024); deviations are listed in the runbook.

Proof (live, against the real DB): enqueue → claim A → claim B refused (exit 5, {task: null}) → lane assign → bind → foreign heartbeat refused → checkpoint → complete; plus lease-expiry reclaim (2 s lease; second worker refused, then claimed after expiry). All states read back from muse-queue directly. Cargo tests: fleet-queue 79+2 green.

Runbook: doc/fleet/queue-turso-cutover.md — cutover steps, rollback, interaction with the (unaffected) PG staged-recovery sequence, the full deviation list, and the what-still-touches-Postgres inventory for the delete-the-project checklist.


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

…UE_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.
@dezren39
dezren39 requested a review from a team as a code owner November 7, 2026 03:50
@coderabbitai

coderabbitai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 20 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 343fb28c-2571-43c7-9950-2ffd95a81384
Commits

Reviewing files that changed from the base of the PR and between 3c74170 and 953d1c3.

Files ignored due to path filters: 1

  • pkgs/fleet/Cargo.lock is excluded by !**/*.lock
Files selected for processing: 6

  • doc/fleet/queue-turso-cutover.md
  • pkgs/fleet/crates/fleet-queue/src/client.rs
  • pkgs/fleet/crates/fleet-queue/src/fallback.rs
  • pkgs/fleet/crates/fleet-queue/src/lib.rs
  • pkgs/fleet/crates/fleet-queue/src/queue_broker.rs
  • pkgs/fleet/crates/fleet-queue/src/turso_queue.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-07T04:21:15.852649Z 953d1c3 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: af68be5988

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +807 to +809
"SELECT {TASK_COLS} FROM tasks \
WHERE queue = ? AND worker_id = ? AND status = 'claimed' \
ORDER BY claimed_at DESC LIMIT 1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Return the exact row modified by the claim statement

When two requests claim tasks for the same worker and queue, this SELECT can return the same task even though the UPDATEs claimed different tasks. Concurrent requests can both observe the latest claim, and even sequential requests within one second can tie because claimed_at has second resolution. The selected ID then drives lease creation and binding cleanup, leaving another task claimed but never returned to its worker. Return the modified row directly with UPDATE ... RETURNING instead of rediscovering it by worker and timestamp.

Useful? React with 👍 / 👎.

Comment on lines +1448 to +1449
"UPDATE tasks SET status = 'done', lease_until = NULL, result = ?, \
updated_at = ? WHERE id = ?",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make ownership checks and task transitions atomic

If another request cancels or expires and reclaims a task after claimed_by reads it, this ID-only UPDATE still lets the original worker mark the task done, and the subsequent DELETE removes the replacement worker's lease. The broker processes requests in separate threads, while each t.exec is a separate HTTP operation with no surrounding transaction. Heartbeat, checkpoint, park, block, and fail have the same stale-guard pattern. Recheck ownership and status in the mutation and keep the associated lease changes atomic so stale requests cannot modify a replacement claim.

Useful? React with 👍 / 👎.

Comment on lines +1198 to +1199
let (not_before, park_kind) = match req_str(req, "not_before") {
Some(nb) => (nb.to_string(), "absolute"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize absolute timestamps before storing them as text

When a caller supplies an absolute not_before with a timezone offset, this stores it verbatim, but claim compares it lexicographically against UTC strings produced by now_iso(). For example, 2026-11-07T10:00:00-06:00 becomes eligible at 10:00 UTC instead of 16:00 UTC. The existing client forwards --not-before unchanged, whereas the Postgres function accepted a timestamptz and compared actual instants. Parse and normalize absolute timestamps to the backend's canonical UTC representation before storage; enqueue's packet timestamp needs the same treatment.

Useful? React with 👍 / 👎.

Comment on lines +932 to +935
"direct"
};
let now = now_iso();
t.exec(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize queue-wide lane allocation

When multiple tasks receive lane assignments concurrently, their requests can read identical o_count and d_count values before any inserts occur, causing all of them to choose the same lane and skewing the opencode/direct experiment. Single-writer serialization of individual INSERTs does not serialize the earlier count reads. The recovered Postgres implementation in pm-stack/opencode-claimant/migration-0021.sql explicitly acquires a queue-scoped transaction advisory lock before counting and inserting. Preserve that serialization around the entire allocation operation.

Useful? React with 👍 / 👎.

…st-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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0d66f51d08

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

"UPDATE repo_task_lane_ledger SET \
executed_lane = COALESCE(?, executed_lane), \
fallback_reason = COALESCE(?, fallback_reason), \
session_id = COALESCE(?, session_id), updated_at = ? \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep cleared bindings cleared when recording execution

When an OpenCode worker parks or transiently fails a task with execution.session_id—as instructed in pm-stack/opencode-claimant/prompt.md:229–232—the transition clears the binding from both task progress and the ledger, but the subsequent verb_with_execution call restores the old session ID here. The next claim cannot clear that ledger binding because clear_binding only checks the already-cleared progress.session_id; /bind then rejects the replacement session as conflicting with the old one. This prevents ordinarily parked or retried OpenCode tasks from launching their next session. Preserve execution history without restoring the active binding on released tasks, or clear residual ledger bindings unconditionally on a fresh claim.

Useful? React with 👍 / 👎.

…nent 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 48a5855d5f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +718 to +721
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', ?, ?, '{}', '{}', ?, ?)",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Make dedupe checks atomic with task insertion

When two producers enqueue the same packet concurrently, both requests can pass the preceding existence check before either INSERT executes. Since tasks_queue_dedupe is explicitly nonunique, both inserts succeed and create independently claimable tasks for the same dedupe key, allowing duplicate remediation or PR work. Make the existence check and insertion atomic, for example with a conditional INSERT or a transaction that serializes the operation, while still permitting historical duplicates during import.

Useful? React with 👍 / 👎.

Comment on lines +1079 to +1084
let resp = call(
"/block",
&json!({
"task_id": task_id,
"worker": worker,
"reason_class": "fallback_held",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Defer fallback-held tasks instead of permanently blocking them

If the fallback holder subsequently disappears, lets its lease expire, or releases the issue with outcome=free, this /block transition leaves the primary task permanently unclaimable. In the Turso backend, verb_block removes its lease and sets status='blocked', while claim only selects queued or parked tasks; fallback::cmd_release only updates GitHub and does not unblock the primary task. Use a retryable park/defer transition or add reconciliation that restores eligibility once the fallback claim is no longer live.

Useful? React with 👍 / 👎.

@dezren39
dezren39 merged commit b88bb02 into main Nov 7, 2026
4 checks passed
@dezren39
dezren39 deleted the queue/6741-turso-backend branch November 7, 2026 04:34
dezren39 pushed a commit that referenced this pull request Nov 7, 2026
…#5690)

Stacked on #6755 (queue/6741-turso-backend). Resolves the agent.events blocker left by the queue-core Turso backend: the stream stays blocked only where Postgres is genuinely required (historical export), everything else now exists behind the same QUEUE_BROKER_BACKEND=turso selection. The Postgres dispatch and the production default are untouched.

turso_queue.rs: events indexes (kind, created_at) and (created_at) in the idempotent schema ensure; POST /events-append (sink for non-queue writers), /events-seen (the event_seen ready-condition primitive replacing the revalidate_parked_tasks EXISTS subquery), /events-count (observability parity), /events-prune (prune_events port, self-logging); /health restores terminal_events_24h/7d per queue via the local events-join-tasks query (the repo_queue_health view fields). Unit tests for append parsing and prune cutoff.

doc/fleet/agent-events-turso.md: full writer/reader inventory (evidence: hatch-personal consumer-audit-5690), the coupling verdict, and the C1-C7 cutover procedure covering the github-ci Edge Function and fleet-fetch AGENT_EVENTS_SINK flips, the broker-side revalidator sweeper design, the PG-gated historical import at a max(id) watermark, prune and backup re-pointing. queue-turso-cutover.md cross-references it.

Verified live against muse-queue with a side broker instance (own port/socket): append returned id 10, events-seen hit/miss correct, counts correct, kind-required validation fires, prune at keep_days=3650 deleted 0 and self-logged, health rows carry terminal_events_24h/7d = 2 from the proof cycle; independent turso CLI readback shows rows 10-11 and both new indexes. cargo test -p fleet-queue --features queue-broker --lib: 75 passed. cargo clippy blocked by a pre-existing sccache/rustc version clash in this environment (E0514 on untouched crates); cargo fmt --check disagrees with the whole branch under this toolchain (24 hunks incl. untouched files), so style follows the file as-is.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant