diff --git a/pm-stack/opencode-claimant/migration-0026.sql b/pm-stack/opencode-claimant/migration-0026.sql new file mode 100644 index 0000000000..5e1efb4c3d --- /dev/null +++ b/pm-stack/opencode-claimant/migration-0026.sql @@ -0,0 +1,166 @@ +-- migration-0026: restore the guarded lane-session recovery modes in +-- bind_repo_task_lane_session (#5400). +-- +-- migration-0022 introduced two narrowly reserved recovery modes for +-- the opencode claimant: when a bound session is verified deleted +-- while still zero-message, or verified absent from the server, the +-- claimant calls bind with p_launched_by set to +-- 'opencode-claimant-recovery:zero-message-deleted' or +-- 'opencode-claimant-recovery:gone-session' and p_session_id set to +-- the PRIOR session id. The function compare-and-clears that id +-- against BOTH agent.tasks.progress and agent.repo_task_lane_ledger +-- before clearing either binding, records stage 'launch_failed' on +-- the task, and consumes one attempt. +-- +-- The migration-0023 record copy rewrote the function without the +-- recovery branches, and migration-0024 (the current definition) +-- kept that shape: its claimed + live-lease guard now rejects every +-- recovery call, because prompt.md only invokes recovery AFTER the +-- lease has expired. The claimant's documented recovery operation +-- (#4758) therefore fails against the recorded function contract. +-- +-- This migration is migration-0024's bind_repo_task_lane_session +-- body with the migration-0022 recovery branch restored ahead of +-- the normal-bind guard. Nothing else changes: +-- +-- * Task-row-first lock order (0024, Codex finding 4465191796) is +-- preserved in both branches: the task row is locked FOR UPDATE +-- before the ledger row is touched; the recovery branch then +-- locks the ledger row FOR UPDATE, as 0022 did. +-- * The normal branch is migration-0024 unchanged: a normal bind +-- still requires a claimed task with a live lease. +-- * Recovery-mode decisions (the point triage task 10034 left open): +-- recovery requires status 'claimed' AND an expired lease +-- (lease_until null or <= now()). prompt.md invokes recovery only +-- after lease expiry, and a live lease means the bound session's +-- launch window is still owned — a recovery call against a live +-- lease is refused, so a stale claimant can never clear a binding +-- whose replacement may still legitimately launch. Recovery also +-- still requires p_worker = 'opencode-claimant', the prior +-- session id present in BOTH stores (any mismatch raises and +-- leaves both stores unchanged), and attempts remaining. +-- +-- Launch eligibility after recovery: recovery deliberately does +-- NOT renew the lease or change the task status. The recovered row +-- is claimed with an expired lease and stage 'launch_failed', which +-- is the broker's handoff shape: lease expiry returns such a row to +-- the handoff sink, and the claimant collects it there with a fresh +-- claim (a new live lease) before launching the replacement session +-- and binding it through the normal branch above. Renewing the +-- lease inside recovery would diverge from the live bind contract, +-- which renews nothing at bind or recovery time. The test file +-- covers this full sequence (scenario S9). +-- +-- revalidate_parked_tasks is not redefined here: migration-0024's +-- definition stands. + +CREATE OR REPLACE FUNCTION agent.bind_repo_task_lane_session(p_task_id bigint, p_worker text, p_session_id text, p_launched_by text DEFAULT 'opencode-claimant'::text) + RETURNS agent.repo_task_lane_ledger + LANGUAGE plpgsql +AS $function$ +declare + t agent.tasks; + row_out agent.repo_task_lane_ledger; + recovery_reason text; +begin + select * into t from agent.tasks where id = p_task_id for update; + if not found then + raise exception 'bind_repo_task_lane_session: task % does not exist', p_task_id; + end if; + + -- Recovery branch (restored from migration-0022): the claimant + -- uses these reserved launched_by values only after the old + -- session is verified deleted-while-zero-message or verified + -- absent, and only after the task lease has expired. Matching + -- both stores before changing either makes recovery an atomic + -- compare-and-clear rather than a progress-only checkpoint. + if p_launched_by in ( + 'opencode-claimant-recovery:zero-message-deleted', + 'opencode-claimant-recovery:gone-session' + ) then + if p_worker is distinct from 'opencode-claimant' then + raise exception 'bind_repo_task_lane_session: recovery must be performed by opencode-claimant'; + end if; + if p_session_id is null or btrim(p_session_id) = '' then + raise exception 'bind_repo_task_lane_session: recovery requires the prior session id'; + end if; + select * into row_out from agent.repo_task_lane_ledger + where task_id = p_task_id for update; + if not found then + raise exception 'bind_repo_task_lane_session: no lane ledger row for task %', p_task_id; + end if; + if t.lease_until is not null and t.lease_until > now() then + raise exception 'bind_repo_task_lane_session: recovery for task % requires an expired lease (lease_until %)', p_task_id, t.lease_until; + end if; + if t.status is distinct from 'claimed' + or coalesce(t.progress ->> 'lane', '') <> 'opencode' + or t.progress ->> 'session_id' is distinct from p_session_id + or row_out.assigned_lane is distinct from 'opencode' + or row_out.session_id is distinct from p_session_id then + raise exception 'bind_repo_task_lane_session: recovery binding mismatch for task %', p_task_id; + end if; + if t.max_attempts is not null + and coalesce(t.attempts, 0) >= t.max_attempts then + raise exception 'bind_repo_task_lane_session: recovery attempts exhausted for task %', p_task_id; + end if; + + recovery_reason := case p_launched_by + when 'opencode-claimant-recovery:zero-message-deleted' + then 'verified zero-message session deleted before recovery' + else 'bound session verified absent before recovery' + end; + + update agent.repo_task_lane_ledger + set session_id = null, updated_at = now() + where task_id = p_task_id + returning * into row_out; + update agent.tasks + set attempts = coalesce(attempts, 0) + 1, + progress = coalesce(progress, '{}'::jsonb) + || jsonb_build_object( + 'session_id', null::text, + 'launched_by', null::text, + 'stage', 'launch_failed', + 'launch_failed_session_id', p_session_id, + 'launch_failed_at', now(), + 'launch_failed_reason', recovery_reason), + updated_at = now() + where id = p_task_id; + insert into agent.events (worker_id, task_id, kind, detail) + values (p_worker, p_task_id, 'lane_session_recovered', + jsonb_build_object('session_id', p_session_id, + 'reason', recovery_reason, + 'stage', 'launch_failed', + 'via', 'bind_repo_task_lane_session')); + return row_out; + end if; + + if t.status <> 'claimed' or t.lease_until is null or t.lease_until <= now() then + raise exception 'bind_repo_task_lane_session: task % is not claimed with a live lease (status %, lease_until %)', + p_task_id, t.status, t.lease_until; + end if; + select * into row_out from agent.repo_task_lane_ledger + where task_id = p_task_id; + if not found then + raise exception 'bind_repo_task_lane_session: no lane ledger row for task %', p_task_id; + end if; + if row_out.session_id is not null and row_out.session_id <> p_session_id then + raise exception 'bind_repo_task_lane_session: task % already bound to session %', p_task_id, row_out.session_id; + end if; + update agent.repo_task_lane_ledger + set session_id = p_session_id, updated_at = now() + where task_id = p_task_id + returning * into row_out; + update agent.tasks + set progress = coalesce(progress, '{}'::jsonb) + || jsonb_build_object('session_id', p_session_id, + 'launched_by', p_launched_by), + updated_at = now() + where id = p_task_id; + insert into agent.events (worker_id, task_id, kind, detail) + values (p_worker, p_task_id, 'lane_session_bound', + jsonb_build_object('session_id', p_session_id, + 'launched_by', p_launched_by, + 'via', 'bind_repo_task_lane_session')); + return row_out; +end $function$; diff --git a/pm-stack/opencode-claimant/test/migration-0026.schema.sql b/pm-stack/opencode-claimant/test/migration-0026.schema.sql new file mode 100644 index 0000000000..c81daf70ef --- /dev/null +++ b/pm-stack/opencode-claimant/test/migration-0026.schema.sql @@ -0,0 +1,60 @@ +-- Focused tests for migration-0026 (#5400): the restored guarded +-- recovery modes in agent.bind_repo_task_lane_session. +-- +-- Run via test_migration_0026.sh, which starts a scratch Postgres, +-- applies THIS schema file first, then ../migration-0026.sql, then +-- migration-0026.test.sql (the scenarios) with ON_ERROR_STOP. +-- +-- The schema here is the minimal subset of columns the function +-- touches (the base agent schema predates the record-copy +-- migrations in this directory and lives with the live DB). + +create schema agent; + +create table agent.tasks ( + id bigint primary key, + queue text, + status text, + lease_until timestamptz, + progress jsonb not null default '{}'::jsonb, + attempts integer not null default 0, + max_attempts integer, + worker_id text, + updated_at timestamptz not null default now() +); + +create table agent.repo_task_lane_ledger ( + task_id bigint primary key, + queue text, + assigned_lane text, + executed_lane text, + exclusion_reason text, + assigned_by text, + session_id text, + updated_at timestamptz not null default now() +); + +create table agent.events ( + id bigserial primary key, + worker_id text, + task_id bigint, + kind text, + detail jsonb, + created_at timestamptz not null default now() +); + +-- Seed one claimed opencode-lane task (id 1) bound to ses_old in +-- both stores; p_lease is relative to now() ('-10 minutes' expired, +-- '+10 minutes' live). +create or replace function agent.test_seed(p_lease interval, p_attempts integer, p_max_attempts integer) +returns void language plpgsql as $$ +begin + truncate agent.events, agent.repo_task_lane_ledger, agent.tasks; + insert into agent.tasks (id, queue, status, lease_until, progress, attempts, max_attempts, worker_id) + values (1, 'repo-health-code-pilot', 'claimed', now() + p_lease, + '{"lane": "opencode", "session_id": "ses_old"}'::jsonb, + p_attempts, p_max_attempts, 'repo-worker-code'); + insert into agent.repo_task_lane_ledger (task_id, queue, assigned_lane, assigned_by, session_id) + values (1, 'repo-health-code-pilot', 'opencode', 'repo-worker-code', 'ses_old'); +end $$; + diff --git a/pm-stack/opencode-claimant/test/migration-0026.test.sql b/pm-stack/opencode-claimant/test/migration-0026.test.sql new file mode 100644 index 0000000000..8270d55095 --- /dev/null +++ b/pm-stack/opencode-claimant/test/migration-0026.test.sql @@ -0,0 +1,203 @@ +-- Focused tests for migration-0026 (#5400): the restored guarded +-- recovery modes in agent.bind_repo_task_lane_session. +-- +-- Scenarios only; the minimal agent schema and the agent.test_seed +-- helper live in migration-0026.schema.sql. Every scenario asserts +-- with the oracle named in its comment; a failed assertion raises +-- and fails the whole run (ON_ERROR_STOP). + +-- S1 (oracle: the migration-0022 recovery contract): zero-message +-- recovery after lease expiry atomically clears BOTH bindings, +-- consumes one attempt, records launch_failed, and emits the event. +do $$ +begin + perform agent.test_seed('-10 minutes', 1, 4); + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_old', + 'opencode-claimant-recovery:zero-message-deleted'); + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) is not null then + raise exception 'TEST FAIL S1: ledger binding not cleared'; + end if; + if (select progress ->> 'session_id' from agent.tasks where id = 1) is not null + or (select progress ->> 'stage' from agent.tasks where id = 1) <> 'launch_failed' + or (select progress ->> 'launch_failed_session_id' from agent.tasks where id = 1) <> 'ses_old' + or (select progress ->> 'launch_failed_reason' from agent.tasks where id = 1) + <> 'verified zero-message session deleted before recovery' then + raise exception 'TEST FAIL S1: task progress does not record the recovery'; + end if; + if (select attempts from agent.tasks where id = 1) <> 2 then + raise exception 'TEST FAIL S1: recovery did not consume one attempt'; + end if; + if not exists (select 1 from agent.events where task_id = 1 and kind = 'lane_session_recovered') then + raise exception 'TEST FAIL S1: lane_session_recovered event missing'; + end if; +end $$; + +-- S2 (oracle: same contract, gone-session reason text). +do $$ +begin + perform agent.test_seed('-10 minutes', 0, 4); + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_old', + 'opencode-claimant-recovery:gone-session'); + if (select progress ->> 'launch_failed_reason' from agent.tasks where id = 1) + <> 'bound session verified absent before recovery' then + raise exception 'TEST FAIL S2: gone-session reason not recorded'; + end if; + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) is not null then + raise exception 'TEST FAIL S2: ledger binding not cleared'; + end if; +end $$; + +-- S3 (oracle: compare-and-clear guard): a mismatched prior session +-- id refuses and leaves BOTH stores byte-identical. +do $$ +declare v_msg text; +begin + perform agent.test_seed('-10 minutes', 1, 4); + begin + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_other', + 'opencode-claimant-recovery:gone-session'); + raise exception 'TEST FAIL S3: mismatched recovery was accepted'; + exception when others then + v_msg := sqlerrm; + if v_msg like 'TEST FAIL%' then raise; end if; + if v_msg not like '%recovery binding mismatch%' then + raise exception 'TEST FAIL S3: wrong refusal: %', v_msg; + end if; + end; + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) <> 'ses_old' + or (select progress ->> 'session_id' from agent.tasks where id = 1) <> 'ses_old' + or (select attempts from agent.tasks where id = 1) <> 1 then + raise exception 'TEST FAIL S3: a store changed on a refused recovery'; + end if; +end $$; + +-- S4 (oracle: the #5400 lease decision — prompt.md invokes recovery +-- only after expiry): recovery against a LIVE lease refuses and +-- changes nothing. +do $$ +declare v_msg text; +begin + perform agent.test_seed('+10 minutes', 1, 4); + begin + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_old', + 'opencode-claimant-recovery:zero-message-deleted'); + raise exception 'TEST FAIL S4: recovery over a live lease was accepted'; + exception when others then + v_msg := sqlerrm; + if v_msg like 'TEST FAIL%' then raise; end if; + if v_msg not like '%requires an expired lease%' then + raise exception 'TEST FAIL S4: wrong refusal: %', v_msg; + end if; + end; + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) <> 'ses_old' then + raise exception 'TEST FAIL S4: ledger changed on a refused recovery'; + end if; +end $$; + +-- S5 (oracle: recovery is the claimant's operation alone). +do $$ +declare v_msg text; +begin + perform agent.test_seed('-10 minutes', 1, 4); + begin + perform agent.bind_repo_task_lane_session( + 1, 'repo-worker-code', 'ses_old', + 'opencode-claimant-recovery:gone-session'); + raise exception 'TEST FAIL S5: recovery by a non-claimant worker was accepted'; + exception when others then + v_msg := sqlerrm; + if v_msg like 'TEST FAIL%' then raise; end if; + if v_msg not like '%recovery must be performed by opencode-claimant%' then + raise exception 'TEST FAIL S5: wrong refusal: %', v_msg; + end if; + end; +end $$; + +-- S6 (oracle: attempts accounting): recovery with attempts +-- exhausted refuses. +do $$ +declare v_msg text; +begin + perform agent.test_seed('-10 minutes', 4, 4); + begin + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_old', + 'opencode-claimant-recovery:gone-session'); + raise exception 'TEST FAIL S6: recovery with attempts exhausted was accepted'; + exception when others then + v_msg := sqlerrm; + if v_msg like 'TEST FAIL%' then raise; end if; + if v_msg not like '%recovery attempts exhausted%' then + raise exception 'TEST FAIL S6: wrong refusal: %', v_msg; + end if; + end; +end $$; + +-- S7 (oracle: migration-0024 normal-bind contract, unchanged): a +-- normal bind with a claimed task and a live lease binds both +-- stores and emits lane_session_bound. +do $$ +begin + perform agent.test_seed('+10 minutes', 1, 4); + update agent.repo_task_lane_ledger set session_id = null where task_id = 1; + update agent.tasks set progress = '{"lane": "opencode"}'::jsonb where id = 1; + perform agent.bind_repo_task_lane_session(1, 'opencode-claimant', 'ses_new', 'opencode-claimant'); + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) <> 'ses_new' + or (select progress ->> 'session_id' from agent.tasks where id = 1) <> 'ses_new' then + raise exception 'TEST FAIL S7: normal bind did not bind both stores'; + end if; + if not exists (select 1 from agent.events where task_id = 1 and kind = 'lane_session_bound') then + raise exception 'TEST FAIL S7: lane_session_bound event missing'; + end if; +end $$; + +-- S8 (oracle: migration-0024 live-lease guard): a normal bind after +-- lease expiry still refuses. +do $$ +declare v_msg text; +begin + perform agent.test_seed('-10 minutes', 1, 4); + update agent.repo_task_lane_ledger set session_id = null where task_id = 1; + update agent.tasks set progress = '{"lane": "opencode"}'::jsonb where id = 1; + begin + perform agent.bind_repo_task_lane_session(1, 'opencode-claimant', 'ses_new', 'opencode-claimant'); + raise exception 'TEST FAIL S8: normal bind over an expired lease was accepted'; + exception when others then + v_msg := sqlerrm; + if v_msg like 'TEST FAIL%' then raise; end if; + if v_msg not like '%not claimed with a live lease%' then + raise exception 'TEST FAIL S8: wrong refusal: %', v_msg; + end if; + end; +end $$; + +-- S9 (oracle: the full relaunch sequence, per the migration-0026 +-- header): recovery, then the broker's expiry/collection +-- transition (the recovered row returns via the handoff sink and +-- is collected under a FRESH claim lease), then the normal bind of +-- the replacement session succeeds against that live lease. +do $$ +begin + perform agent.test_seed('-10 minutes', 1, 4); + perform agent.bind_repo_task_lane_session( + 1, 'opencode-claimant', 'ses_old', + 'opencode-claimant-recovery:gone-session'); + -- Simulate the broker transition: expired claimed row with the + -- launch_failed handoff shape returns to the sink and is + -- collected by the claimant under a fresh lease. + update agent.tasks + set status = 'claimed', worker_id = 'opencode-claimant', + lease_until = now() + interval '2700 seconds' + where id = 1; + perform agent.bind_repo_task_lane_session(1, 'opencode-claimant', 'ses_new', 'opencode-claimant'); + if (select session_id from agent.repo_task_lane_ledger where task_id = 1) <> 'ses_new' + or (select progress ->> 'session_id' from agent.tasks where id = 1) <> 'ses_new' then + raise exception 'TEST FAIL S9: normal bind after recovery + fresh claim did not bind'; + end if; +end $$; + +\echo 'migration-0026 tests: all 9 scenarios passed' diff --git a/pm-stack/opencode-claimant/test/test_migration_0026.sh b/pm-stack/opencode-claimant/test/test_migration_0026.sh new file mode 100755 index 0000000000..294c1d62e9 --- /dev/null +++ b/pm-stack/opencode-claimant/test/test_migration_0026.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Runner for the migration-0026 focused tests (#5400). +# +# Starts a throwaway Postgres cluster in a mktemp directory (socket +# only, no TCP), applies the minimal schema, then ../migration-0026.sql, +# then runs the scenario file in migration-0026.test.sql with +# ON_ERROR_STOP. Exit 0 = all scenarios passed. The cluster and its +# data directory are removed on exit; nothing touches any live DB. +set -euo pipefail + +cd "$(dirname "$0")" + +PGROOT="$(mktemp -d)" +PORT=55439 +cleanup() { + pg_ctl -D "$PGROOT/data" -m immediate stop >/dev/null 2>&1 || true + rm -rf "$PGROOT" +} +trap cleanup EXIT + +initdb -D "$PGROOT/data" -U postgres --auth=trust >/dev/null +pg_ctl -D "$PGROOT/data" -l "$PGROOT/pg.log" -w \ + -o "-k $PGROOT -p $PORT -c listen_addresses=''" start >/dev/null +createdb -h "$PGROOT" -p "$PORT" -U postgres migration_0026_test + +psql -h "$PGROOT" -p "$PORT" -U postgres -d migration_0026_test \ + -v ON_ERROR_STOP=1 -q \ + -f migration-0026.schema.sql \ + -f ../migration-0026.sql \ + -f migration-0026.test.sql + +echo "test_migration_0026.sh: PASS"