-- #308: move the default queue-storage substrate DDL out of -- QueueStorage::prepare_schema() in Rust and into a SQL helper function -- that `awa migrate` runs as part of the canonical migration set. -- -- Contract -- -------- -- After this migration runs, `awa.install_queue_storage_substrate(p_schema)` -- is the single source of truth for the per-schema queue-storage substrate -- objects (sequences, ring-state singletons, partitioned ready/done/lease -- tables, lane indexes, claim_ready_runtime() function, etc). It is callable -- from Rust (`QueueStorage::prepare_schema`), from `awa migrate --sql` -- output, from the Python client, and from operators driving DDL directly. -- -- The default `awa` substrate is migration-owned and default-shaped: -- (queue_slot_count=16, lease_slot_count=8, claim_slot_count=8, -- lease_claim_receipts=TRUE). Operators wanting non-default slot counts -- or the legacy non-receipts claim path MUST use a custom queue-storage -- schema; the helper rejects non-default configs against `p_schema='awa'` -- with errcode 22023. -- -- The helper is SECURITY INVOKER and explicitly revokes EXECUTE from -- PUBLIC — runtime roles MUST NOT gain DDL through it. The helper takes a per-schema -- advisory xact lock named `awa.queue_storage.install:{p_schema}` to -- serialize concurrent installs (matches the lock pattern previously -- held in Rust). -- -- Deliberately not owned by this helper: -- - The `awa.runtime_storage_backends` cross-schema table is owned by the -- v012 migration. Activation/finalization paths seed or update the -- `queue_storage` row. -- - The non-additive legacy upgrade edge cases (open_receipt_claims drop, -- lease_claims / lease_claim_batches / lease_claim_closures / lease_claim_closure_batches -- rename-and-rebuild from a -- non-partitioned shape, queue_count_snapshots drop) — these are -- one-shot upgrade fixups that don't belong in a forward-only DDL -- function. They remain in `prepare_schema()` for custom schemas; the -- default `awa` migration step runs the `awa`-specific copy separately. CREATE OR REPLACE FUNCTION awa.refresh_lane_sequence_helpers(p_schema TEXT) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog AS $refresh$ DECLARE v_schema_owner OID; v_function REGPROCEDURE; v_function_owner OID; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; BEGIN EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.ensure_lane_sequences( p_queue TEXT, p_priority SMALLINT, p_enqueue_shard SMALLINT ) RETURNS VOID LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_enqueue_seq TEXT := %1$I.queue_lane_sequence_name( 'queue_enqueue_seq', p_queue, p_priority, p_enqueue_shard ); v_claim_seq TEXT := %1$I.queue_lane_sequence_name( 'queue_claim_seq', p_queue, p_priority, p_enqueue_shard ); BEGIN IF to_regclass(format('%%I.%%I', %1$L, v_enqueue_seq)) IS NULL THEN IF has_function_privilege( to_regprocedure(format('%%I.provision_lane_sequences(text,smallint,smallint)', %1$L)), 'EXECUTE' ) THEN PERFORM %1$I.provision_lane_sequences(p_queue, p_priority, p_enqueue_shard); ELSIF NOT has_schema_privilege(current_user, %1$L, 'CREATE') THEN RAISE EXCEPTION 'lane sequence %%.%% has not been provisioned', %1$L, v_enqueue_seq USING ERRCODE = '42501', HINT = 'Run awa migrate, or awa storage prepare-queue as the migrator, before starting producers or workers.'; ELSE EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %%I.%%I AS bigint START WITH 1 MINVALUE 1 CACHE 1', %1$L, v_enqueue_seq ); END IF; END IF; IF to_regclass(format('%%I.%%I', %1$L, v_claim_seq)) IS NULL THEN IF has_function_privilege( to_regprocedure(format('%%I.provision_lane_sequences(text,smallint,smallint)', %1$L)), 'EXECUTE' ) THEN PERFORM %1$I.provision_lane_sequences(p_queue, p_priority, p_enqueue_shard); ELSIF NOT has_schema_privilege(current_user, %1$L, 'CREATE') THEN RAISE EXCEPTION 'lane sequence %%.%% has not been provisioned', %1$L, v_claim_seq USING ERRCODE = '42501', HINT = 'Run awa migrate, or awa storage prepare-queue as the migrator, before starting producers or workers.'; ELSE EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %%I.%%I AS bigint START WITH 1 MINVALUE 1 CACHE 1', %1$L, v_claim_seq ); END IF; END IF; UPDATE %1$I.queue_enqueue_heads SET seq_name = v_enqueue_seq WHERE queue = p_queue AND priority = p_priority AND enqueue_shard = p_enqueue_shard AND seq_name IS DISTINCT FROM v_enqueue_seq; UPDATE %1$I.queue_claim_heads SET seq_name = v_claim_seq WHERE queue = p_queue AND priority = p_priority AND enqueue_shard = p_enqueue_shard AND seq_name IS DISTINCT FROM v_claim_seq; END; $func$ $ddl$, p_schema ); -- set_sequence_next is defined here, beside the triggers that call it, -- so a migration refreshing these helpers refreshes it too. EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.set_sequence_next(p_seq_name TEXT, p_next BIGINT) RETURNS VOID LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_lock_key TEXT; BEGIN IF p_seq_name IS NULL THEN RAISE EXCEPTION 'lane sequence name is NULL' USING ERRCODE = '55000'; END IF; v_lock_key := format('%%I.%%I', %1$L, p_seq_name); -- `setval` is not a compare-and-swap. Serialize it against -- reservation-side block allocation so this helper's "move to at -- least p_next" contract cannot rewind a hot enqueue sequence. -- Every way out of the block releases the session lock, -- including a cancel or statement timeout, which OTHERS does not -- catch; see queue_enqueue_head_sequence_sync. BEGIN PERFORM pg_advisory_lock(hashtextextended(v_lock_key, 0)); p_next := GREATEST(p_next, %1$I.sequence_next_value(p_seq_name)); IF p_next <= 1 THEN EXECUTE format( 'SELECT setval(%%L::regclass, 1, false)', format('%%I.%%I', %1$L, p_seq_name) ); ELSE EXECUTE format( 'SELECT setval(%%L::regclass, %%s, true)', format('%%I.%%I', %1$L, p_seq_name), p_next - 1 ); END IF; PERFORM pg_advisory_unlock(hashtextextended(v_lock_key, 0)); EXCEPTION WHEN OTHERS OR query_canceled THEN IF EXISTS ( SELECT 1 FROM pg_catalog.pg_locks AS held WHERE held.locktype = 'advisory' AND held.pid = pg_backend_pid() AND held.granted AND held.objsubid = 1 AND held.classid = ((hashtextextended(v_lock_key, 0) >> 32) & 4294967295)::oid AND held.objid = (hashtextextended(v_lock_key, 0) & 4294967295)::oid ) THEN PERFORM pg_advisory_unlock(hashtextextended(v_lock_key, 0)); END IF; RAISE; END; END; $func$ $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.queue_enqueue_head_sequence_sync() RETURNS TRIGGER LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_seq_name TEXT := %1$I.queue_lane_sequence_name( 'queue_enqueue_seq', NEW.queue, NEW.priority, NEW.enqueue_shard ); v_qualified_seq TEXT := format('%%I.%%I', %1$L, v_seq_name); v_count BIGINT; v_start BIGINT; BEGIN IF to_regclass(format('%%I.%%I', %1$L, v_seq_name)) IS NULL THEN IF has_function_privilege( to_regprocedure(format('%%I.provision_lane_sequences(text,smallint,smallint)', %1$L)), 'EXECUTE' ) THEN PERFORM %1$I.provision_lane_sequences(NEW.queue, NEW.priority, NEW.enqueue_shard); ELSIF NOT has_schema_privilege(current_user, %1$L, 'CREATE') THEN RAISE EXCEPTION 'lane sequence %%.%% has not been provisioned', %1$L, v_seq_name USING ERRCODE = '42501', HINT = 'Run awa migrate, or awa storage prepare-queue as the migrator, before starting producers or workers.'; ELSE EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %%I.%%I AS bigint START WITH 1 MINVALUE 1 CACHE 1', %1$L, v_seq_name ); END IF; END IF; NEW.seq_name := v_seq_name; IF TG_OP = 'UPDATE' AND NEW.next_seq IS DISTINCT FROM OLD.next_seq AND NEW.next_seq > OLD.next_seq THEN v_count := NEW.next_seq - OLD.next_seq; -- A pooled connection keeps a session lock it leaks, which -- would stall this lane's reservations, so every way out of -- the block releases it, including a cancel or statement -- timeout, which OTHERS does not catch. The lock is taken -- inside the block and the handler checks pg_locks, because -- the error can also come before the lock is granted. BEGIN PERFORM pg_advisory_lock(hashtextextended(v_qualified_seq, 0)); EXECUTE format( 'SELECT nextval(%%L::regclass)::bigint', v_qualified_seq ) INTO v_start; IF v_count > 1 THEN EXECUTE format( 'SELECT setval(%%L::regclass, %%s, true)', v_qualified_seq, v_start + v_count - 1 ); END IF; PERFORM pg_advisory_unlock(hashtextextended(v_qualified_seq, 0)); EXCEPTION WHEN OTHERS OR query_canceled THEN IF EXISTS ( SELECT 1 FROM pg_catalog.pg_locks AS held WHERE held.locktype = 'advisory' AND held.pid = pg_backend_pid() AND held.granted AND held.objsubid = 1 AND held.classid = ((hashtextextended(v_qualified_seq, 0) >> 32) & 4294967295)::oid AND held.objid = (hashtextextended(v_qualified_seq, 0) & 4294967295)::oid ) THEN PERFORM pg_advisory_unlock(hashtextextended(v_qualified_seq, 0)); END IF; RAISE; END; NEW.next_seq := v_start + v_count; ELSE PERFORM %1$I.set_sequence_next(v_seq_name, NEW.next_seq); END IF; RETURN NEW; END; $func$ $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.queue_claim_head_sequence_sync() RETURNS TRIGGER LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_seq_name TEXT := %1$I.queue_lane_sequence_name( 'queue_claim_seq', NEW.queue, NEW.priority, NEW.enqueue_shard ); BEGIN IF to_regclass(format('%%I.%%I', %1$L, v_seq_name)) IS NULL THEN IF has_function_privilege( to_regprocedure(format('%%I.provision_lane_sequences(text,smallint,smallint)', %1$L)), 'EXECUTE' ) THEN PERFORM %1$I.provision_lane_sequences(NEW.queue, NEW.priority, NEW.enqueue_shard); ELSIF NOT has_schema_privilege(current_user, %1$L, 'CREATE') THEN RAISE EXCEPTION 'lane sequence %%.%% has not been provisioned', %1$L, v_seq_name USING ERRCODE = '42501', HINT = 'Run awa migrate, or awa storage prepare-queue as the migrator, before starting producers or workers.'; ELSE EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %%I.%%I AS bigint START WITH 1 MINVALUE 1 CACHE 1', %1$L, v_seq_name ); END IF; END IF; NEW.seq_name := v_seq_name; IF TG_OP = 'INSERT' THEN PERFORM %1$I.set_sequence_next(v_seq_name, NEW.claim_seq); END IF; RETURN NEW; END; $func$ $ddl$, p_schema ); -- Lane sequences are created by the schema owner through these two -- SECURITY DEFINER functions, whichever role first touches the lane, so -- every runtime role can use them. Their grants mirror the head table each -- sequence backs (see awa.lane_sequence_problems); they never depend on -- the creating role's default privileges. EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.provision_lane_sequences( p_queue TEXT, p_priority SMALLINT, p_enqueue_shard SMALLINT ) RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $func$ DECLARE v_seq_name TEXT; v_grant TEXT; BEGIN IF p_queue IS NULL OR p_priority IS NULL OR p_enqueue_shard IS NULL OR p_enqueue_shard NOT BETWEEN 0 AND 63 THEN RAISE EXCEPTION 'invalid queue lane: queue %%, priority %%, enqueue shard %%', quote_nullable(p_queue), p_priority, p_enqueue_shard USING ERRCODE = '22023'; END IF; -- The lane lock QueueStorage takes before it writes lane rows, so -- concurrent first touches of one lane create its sequences once. PERFORM pg_advisory_xact_lock(hashtextextended( format('%%s:%%s:%%s:%%s', %1$L, p_queue, p_priority, p_enqueue_shard), 0 )); FOREACH v_seq_name IN ARRAY ARRAY[ %1$I.queue_lane_sequence_name('queue_enqueue_seq', p_queue, p_priority, p_enqueue_shard), %1$I.queue_lane_sequence_name('queue_claim_seq', p_queue, p_priority, p_enqueue_shard) ] LOOP IF to_regclass(format('%%I.%%I', %1$L, v_seq_name)) IS NULL THEN EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %%I.%%I AS bigint START WITH 1 MINVALUE 1 CACHE 1', %1$L, v_seq_name ); FOR v_grant IN SELECT unnest(problem.missing_grants) FROM awa.lane_sequence_problems(%1$L, v_seq_name) AS problem WHERE problem.owner = current_user LOOP EXECUTE v_grant; END LOOP; END IF; END LOOP; END; $func$ $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.provision_lane( p_queue TEXT, p_priority SMALLINT, p_enqueue_shard SMALLINT ) RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $func$ BEGIN IF p_queue IS NULL OR p_priority IS NULL OR p_enqueue_shard IS NULL OR p_enqueue_shard NOT BETWEEN 0 AND 63 THEN RAISE EXCEPTION 'invalid queue lane: queue %%, priority %%, enqueue shard %%', quote_nullable(p_queue), p_priority, p_enqueue_shard USING ERRCODE = '22023'; END IF; -- The lane row comes before the lane lock, the order every -- producer takes them in. INSERT INTO %1$I.queue_lanes (queue, priority) VALUES (p_queue, p_priority) ON CONFLICT (queue, priority) DO NOTHING; PERFORM %1$I.provision_lane_sequences(p_queue, p_priority, p_enqueue_shard); -- The head triggers fire before ON CONFLICT and set the lane's -- sequence, so rows that already exist are skipped outright. INSERT INTO %1$I.queue_enqueue_heads (queue, priority, enqueue_shard) SELECT p_queue, p_priority, p_enqueue_shard WHERE NOT EXISTS ( SELECT 1 FROM %1$I.queue_enqueue_heads AS heads WHERE heads.queue = p_queue AND heads.priority = p_priority AND heads.enqueue_shard = p_enqueue_shard ) ON CONFLICT (queue, priority, enqueue_shard) DO NOTHING; INSERT INTO %1$I.queue_claim_heads (queue, priority, enqueue_shard) SELECT p_queue, p_priority, p_enqueue_shard WHERE NOT EXISTS ( SELECT 1 FROM %1$I.queue_claim_heads AS heads WHERE heads.queue = p_queue AND heads.priority = p_priority AND heads.enqueue_shard = p_enqueue_shard ) ON CONFLICT (queue, priority, enqueue_shard) DO NOTHING; PERFORM %1$I.ensure_lane_sequences(p_queue, p_priority, p_enqueue_shard); END; $func$ $ddl$, p_schema ); SELECT namespace.nspowner INTO v_schema_owner FROM pg_namespace AS namespace WHERE namespace.nspname = p_schema; FOREACH v_function IN ARRAY ARRAY[ format('%I.provision_lane_sequences(text,smallint,smallint)', p_schema)::regprocedure, format('%I.provision_lane(text,smallint,smallint)', p_schema)::regprocedure ] LOOP EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO PUBLIC', v_function); SELECT routine.proowner INTO v_function_owner FROM pg_proc AS routine WHERE routine.oid = v_function; IF v_function_owner <> v_schema_owner THEN IF pg_has_role(current_user, v_function_owner, 'USAGE') AND pg_has_role(current_user, v_schema_owner, v_set_mode) THEN EXECUTE format( 'ALTER FUNCTION %s OWNER TO %I', v_function, pg_get_userbyid(v_schema_owner) ); ELSE RAISE WARNING '% is owned by %, not the owner % of schema %; lane sequences it creates will be owned by % too', v_function, pg_get_userbyid(v_function_owner), pg_get_userbyid(v_schema_owner), p_schema, pg_get_userbyid(v_function_owner) USING HINT = format( 'Run awa migrate as a role that can SET ROLE to %s, or as %s itself.', quote_ident(pg_get_userbyid(v_schema_owner)), quote_ident(pg_get_userbyid(v_schema_owner)) ); END IF; END IF; END LOOP; END; $refresh$; REVOKE EXECUTE ON FUNCTION awa.refresh_lane_sequence_helpers(TEXT) FROM PUBLIC; -- Refreshes p_schema's lane helpers from a migration. They are replaced in -- place, which needs their owner's privileges: a migration role that may -- only SET ROLE to the schema's owner (PostgreSQL 16+ INHERIT FALSE) retries -- as that owner, lending it EXECUTE on awa.refresh_lane_sequence_helpers and -- USAGE on awa for the call when it lacks them and taking them back after. A -- role that can do neither keeps the old helpers, with a warning, and the -- function returns false rather than failing the migration. CREATE OR REPLACE FUNCTION awa.refresh_lane_sequence_helpers_as_migrator(p_schema TEXT) RETURNS BOOLEAN LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $refresh$ DECLARE v_owner OID; v_owner_name TEXT; v_previous_role TEXT; v_lent_execute BOOLEAN := false; v_lent_usage BOOLEAN := false; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; BEGIN BEGIN PERFORM awa.refresh_lane_sequence_helpers(p_schema); RETURN true; EXCEPTION WHEN insufficient_privilege THEN NULL; END; SELECT namespace.nspowner INTO v_owner FROM pg_namespace AS namespace WHERE namespace.nspname = p_schema; v_owner_name := pg_get_userbyid(v_owner); -- Everything here runs in one subtransaction, so a failure also undoes -- the lent privileges and the role switch. BEGIN IF v_owner IS NULL OR NOT pg_has_role(current_user, v_owner, v_set_mode) THEN RAISE insufficient_privilege; END IF; IF NOT has_function_privilege(v_owner, 'awa.refresh_lane_sequence_helpers(text)', 'EXECUTE') THEN EXECUTE format('GRANT EXECUTE ON FUNCTION awa.refresh_lane_sequence_helpers(text) TO %I', v_owner_name); v_lent_execute := true; END IF; IF NOT has_schema_privilege(v_owner, 'awa', 'USAGE') THEN EXECUTE format('GRANT USAGE ON SCHEMA awa TO %I', v_owner_name); v_lent_usage := true; END IF; v_previous_role := current_setting('role'); PERFORM set_config('role', v_owner_name, true); PERFORM awa.refresh_lane_sequence_helpers(p_schema); PERFORM set_config('role', v_previous_role, true); IF v_lent_execute THEN EXECUTE format('REVOKE EXECUTE ON FUNCTION awa.refresh_lane_sequence_helpers(text) FROM %I', v_owner_name); END IF; IF v_lent_usage THEN EXECUTE format('REVOKE USAGE ON SCHEMA awa FROM %I', v_owner_name); END IF; RETURN true; EXCEPTION WHEN insufficient_privilege THEN RAISE WARNING 'could not refresh the lane-sequence helpers of schema %: %', p_schema, SQLERRM USING HINT = format( 'Run SELECT awa.refresh_lane_sequence_helpers(%L) as the owner of its lane functions; ' 'that role needs USAGE on schema awa and EXECUTE on the function.', p_schema ); RETURN false; END; END; $refresh$; REVOKE EXECUTE ON FUNCTION awa.refresh_lane_sequence_helpers_as_migrator(TEXT) FROM PUBLIC; -- Lane sequences in p_schema (or the one named p_sequence) that are not owned -- by the schema owner or lack a runtime grant. A lane sequence carries a head -- table's cursor, so whoever may write that head table (INSERT or UPDATE) gets -- USAGE, SELECT and UPDATE on it, and whoever may read it gets SELECT: -- queue_enqueue_seq_* mirror queue_enqueue_heads, queue_claim_seq_* mirror -- queue_claim_heads. missing_grants holds the statements to run as the -- sequence owner; reassign_sql, when the owner is wrong, needs a role that -- holds the current owner's privileges and can SET ROLE to the schema owner. -- repair_roles lists the login roles, superusers aside, that can run both. -- Read-only. CREATE OR REPLACE FUNCTION awa.lane_sequence_problems(p_schema TEXT, p_sequence TEXT DEFAULT NULL) RETURNS TABLE ( sequence_name TEXT, owner TEXT, expected_owner TEXT, missing_grants TEXT[], reassign_sql TEXT, repair_roles TEXT[] ) LANGUAGE sql STABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $problems$ WITH target AS ( SELECT namespace.oid, namespace.nspowner FROM pg_namespace AS namespace WHERE namespace.nspname = p_schema ), lane_sequence AS ( SELECT sequence.oid, sequence.relname::text AS relname, sequence.relowner, sequence.relacl, target.nspowner, CASE WHEN starts_with(sequence.relname::text, 'queue_enqueue_seq_') THEN 'queue_enqueue_heads' ELSE 'queue_claim_heads' END AS head_table FROM target JOIN pg_class AS sequence ON sequence.relnamespace = target.oid WHERE sequence.relkind = 'S' AND sequence.relname ~ '^queue_(enqueue|claim)_seq_[0-9a-f]{32}$' AND (p_sequence IS NULL OR sequence.relname = p_sequence) ), wanted AS ( SELECT DISTINCT lane_sequence.oid, head_privilege.grantee, sequence_privilege.privilege_type FROM lane_sequence JOIN pg_class AS head ON head.relnamespace = (SELECT target.oid FROM target) AND head.relname = lane_sequence.head_table CROSS JOIN LATERAL aclexplode(COALESCE(head.relacl, acldefault('r', head.relowner))) AS head_privilege CROSS JOIN LATERAL unnest( CASE head_privilege.privilege_type WHEN 'SELECT' THEN ARRAY['SELECT'] WHEN 'INSERT' THEN ARRAY['USAGE', 'SELECT', 'UPDATE'] WHEN 'UPDATE' THEN ARRAY['USAGE', 'SELECT', 'UPDATE'] ELSE ARRAY[]::TEXT[] END ) AS sequence_privilege(privilege_type) WHERE head_privilege.grantee <> lane_sequence.nspowner ), missing AS ( SELECT wanted.oid, wanted.grantee, wanted.privilege_type FROM wanted JOIN lane_sequence ON lane_sequence.oid = wanted.oid WHERE NOT EXISTS ( SELECT 1 FROM aclexplode(COALESCE(lane_sequence.relacl, acldefault('S', lane_sequence.relowner))) AS held WHERE held.grantee = wanted.grantee AND held.privilege_type = wanted.privilege_type ) ) SELECT lane_sequence.relname, pg_get_userbyid(lane_sequence.relowner)::text, pg_get_userbyid(lane_sequence.nspowner)::text, ARRAY( SELECT format( 'GRANT %s ON SEQUENCE %I.%I TO %s', string_agg(missing.privilege_type, ', ' ORDER BY missing.privilege_type DESC), p_schema, lane_sequence.relname, CASE missing.grantee WHEN 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(missing.grantee)) END ) FROM missing WHERE missing.oid = lane_sequence.oid GROUP BY missing.grantee ORDER BY 1 ), CASE WHEN lane_sequence.relowner <> lane_sequence.nspowner THEN format( 'ALTER SEQUENCE %I.%I OWNER TO %I', p_schema, lane_sequence.relname, pg_get_userbyid(lane_sequence.nspowner) ) END, ARRAY( SELECT candidate.rolname::text FROM pg_roles AS candidate WHERE candidate.rolcanlogin AND NOT candidate.rolsuper AND pg_has_role(candidate.oid, lane_sequence.relowner, 'USAGE') AND (lane_sequence.relowner = lane_sequence.nspowner OR pg_has_role( candidate.oid, lane_sequence.nspowner, CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END )) ORDER BY candidate.rolname ) FROM lane_sequence WHERE lane_sequence.relowner <> lane_sequence.nspowner OR EXISTS (SELECT 1 FROM missing WHERE missing.oid = lane_sequence.oid) ORDER BY lane_sequence.relname $problems$; -- Give one lane sequence to the schema owner and add its missing runtime -- grants, doing only what the calling role is allowed to: a sequence it -- cannot reassign keeps its owner and still gets the grants when the caller -- holds that owner's privileges. Never raises for a sequence it cannot -- repair. Reassigning takes the sequence's ACCESS EXCLUSIVE lock, which an -- open enqueue or claim on the lane conflicts with, so the lock wait is -- bounded: on timeout nothing changes and the outcome is 'busy'. The lock is -- held until the caller's transaction ends, so callers repair one sequence -- per transaction. Returns no row when the sequence needs nothing, otherwise -- one row: outcome is 'repaired', 'owner_unchanged' (grants complete, owner -- still wrong), 'unrepaired' or 'busy', with the statements still to run. CREATE OR REPLACE FUNCTION awa.repair_lane_sequence(p_schema TEXT, p_sequence TEXT) RETURNS TABLE ( sequence_name TEXT, owner TEXT, expected_owner TEXT, outcome TEXT, missing_grants TEXT[], reassign_sql TEXT, repair_roles TEXT[] ) LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp SET lock_timeout = '300ms' AS $repair$ DECLARE v_problem RECORD; v_remaining RECORD; v_original_role TEXT := current_setting('role'); v_reassigned BOOLEAN := false; v_role_changed BOOLEAN := false; v_busy BOOLEAN := false; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; v_statement TEXT; BEGIN SELECT * INTO v_problem FROM awa.lane_sequence_problems(p_schema, p_sequence) AS problem; IF NOT FOUND THEN RETURN; END IF; BEGIN -- ALTER ... OWNER TO needs the current owner's privileges, SET ROLE to -- the new owner, and the new owner's CREATE on the schema (which a -- schema owner has). Check first so an unrelated owner is skipped -- without waiting for the lock. IF v_problem.reassign_sql IS NOT NULL AND pg_has_role(current_user, to_regrole(quote_ident(v_problem.owner)), 'USAGE') AND pg_has_role(current_user, to_regrole(quote_ident(v_problem.expected_owner)), v_set_mode) THEN BEGIN EXECUTE v_problem.reassign_sql; v_reassigned := true; EXCEPTION WHEN insufficient_privilege THEN NULL; END; END IF; SELECT * INTO v_remaining FROM awa.lane_sequence_problems(p_schema, p_sequence) AS problem; IF FOUND AND cardinality(v_remaining.missing_grants) > 0 AND (pg_has_role(current_user, to_regrole(quote_ident(v_remaining.owner)), 'USAGE') OR v_reassigned) THEN BEGIN IF v_reassigned AND NOT pg_has_role(current_user, to_regrole(quote_ident(v_remaining.owner)), 'USAGE') THEN PERFORM set_config('role', v_remaining.owner, true); v_role_changed := true; END IF; FOREACH v_statement IN ARRAY v_remaining.missing_grants LOOP BEGIN EXECUTE v_statement; EXCEPTION WHEN insufficient_privilege THEN NULL; END; END LOOP; IF v_role_changed THEN PERFORM set_config('role', v_original_role, true); END IF; EXCEPTION WHEN insufficient_privilege THEN NULL; END; END IF; EXCEPTION WHEN lock_not_available THEN v_busy := true; END; SELECT * INTO v_remaining FROM awa.lane_sequence_problems(p_schema, p_sequence) AS problem; sequence_name := v_problem.sequence_name; expected_owner := v_problem.expected_owner; IF FOUND THEN owner := v_remaining.owner; missing_grants := v_remaining.missing_grants; reassign_sql := v_remaining.reassign_sql; repair_roles := v_remaining.repair_roles; outcome := CASE WHEN v_busy THEN 'busy' WHEN cardinality(v_remaining.missing_grants) = 0 THEN 'owner_unchanged' ELSE 'unrepaired' END; ELSE owner := v_problem.expected_owner; missing_grants := ARRAY[]::TEXT[]; reassign_sql := NULL; repair_roles := ARRAY[]::TEXT[]; outcome := 'repaired'; END IF; RETURN NEXT; END $repair$; REVOKE EXECUTE ON FUNCTION awa.repair_lane_sequence(TEXT, TEXT) FROM PUBLIC; -- Retained job output (ADR-048): add the output columns to an existing -- substrate and expose them through terminal_jobs. Called by the installer -- and by migration v052, which does not replay the installer. Each column is -- added only when missing, so a re-run takes no lock on the tables, and the -- cardinality check is NOT VALID: it holds for new batch rows without -- scanning retained history. CREATE OR REPLACE FUNCTION awa.install_queue_storage_job_output(p_schema TEXT) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, awa, public SET quote_all_identifiers = off AS $job_output$ DECLARE v_view REGCLASS := to_regclass(format('%I.terminal_jobs', p_schema)); BEGIN -- When anything is missing, lock in the order terminal_jobs readers do -- (the view, then its tables), so a read that starts mid-migration -- waits instead of deadlocking against the ALTERs. IF v_view IS NOT NULL AND ( NOT EXISTS ( SELECT 1 FROM pg_attribute WHERE attrelid = v_view AND attname = 'output' AND NOT attisdropped ) OR NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conrelid = format('%I.receipt_completion_batches', p_schema)::regclass AND conname = 'receipt_completion_batches_outputs_cardinality' ) ) THEN EXECUTE format( 'LOCK TABLE %1$I.terminal_jobs, %1$I.done_entries, %1$I.receipt_completion_batches IN ACCESS EXCLUSIVE MODE', p_schema ); END IF; IF NOT EXISTS ( SELECT 1 FROM pg_attribute WHERE attrelid = format('%I.done_entries', p_schema)::regclass AND attname = 'output' AND NOT attisdropped ) THEN EXECUTE format('ALTER TABLE %I.done_entries ADD COLUMN IF NOT EXISTS output JSON', p_schema); END IF; IF NOT EXISTS ( SELECT 1 FROM pg_attribute WHERE attrelid = format('%I.receipt_completion_batches', p_schema)::regclass AND attname = 'outputs' AND NOT attisdropped ) THEN EXECUTE format( 'ALTER TABLE %I.receipt_completion_batches ADD COLUMN IF NOT EXISTS outputs JSON[]', p_schema ); END IF; IF NOT EXISTS ( SELECT 1 FROM pg_constraint WHERE conrelid = format('%I.receipt_completion_batches', p_schema)::regclass AND conname = 'receipt_completion_batches_outputs_cardinality' ) THEN EXECUTE format( $ddl$ ALTER TABLE %I.receipt_completion_batches ADD CONSTRAINT receipt_completion_batches_outputs_cardinality CHECK (outputs IS NULL OR completed_count = cardinality(outputs)) NOT VALID $ddl$, p_schema ); END IF; EXECUTE format( $ddl$ CREATE OR REPLACE VIEW %1$I.terminal_jobs AS SELECT done.ready_slot, done.ready_generation, done.job_id, done.kind, done.queue, COALESCE(done.args, ready.args, '{}'::jsonb) AS args, done.state, done.priority, done.attempt, done.run_lease, COALESCE(done.max_attempts, ready.max_attempts, 25::smallint) AS max_attempts, done.lane_seq, done.enqueue_shard, COALESCE(done.run_at, ready.run_at, done.finalized_at) AS run_at, COALESCE(done.attempted_at, ready.attempted_at) AS attempted_at, done.finalized_at, COALESCE(done.created_at, ready.created_at, done.finalized_at) AS created_at, COALESCE(done.unique_key, ready.unique_key) AS unique_key, COALESCE(done.unique_states, ready.unique_states) AS unique_states, COALESCE(done.payload, ready.payload, '{}'::jsonb) AS payload, done.output FROM %1$I.done_entries AS done LEFT JOIN %1$I.ready_entries AS ready ON ready.ready_slot = done.ready_slot AND ready.ready_generation = done.ready_generation AND ready.queue = done.queue AND ready.priority = done.priority AND ready.enqueue_shard = done.enqueue_shard AND ready.lane_seq = done.lane_seq UNION ALL SELECT batch.ready_slot, batch.ready_generation, item.job_id, ready.kind, batch.queue, ready.args, 'completed'::awa.job_state AS state, batch.priority, item.attempt, item.run_lease, ready.max_attempts, item.lane_seq, batch.enqueue_shard, ready.run_at, item.attempted_at, batch.finalized_at, ready.created_at, ready.unique_key, ready.unique_states, COALESCE(ready.payload, '{}'::jsonb) AS payload, -- Subscript rather than unnest, so only matching rows detoast -- the batch's output array. batch.outputs[item.ord] AS output FROM %1$I.receipt_completion_batches AS batch CROSS JOIN LATERAL unnest( batch.job_ids, batch.run_leases, batch.lane_seqs, batch.attempts, batch.attempted_ats ) WITH ORDINALITY AS item(job_id, run_lease, lane_seq, attempt, attempted_at, ord) JOIN %1$I.ready_entries AS ready ON ready.ready_slot = batch.ready_slot AND ready.ready_generation = batch.ready_generation AND ready.queue = batch.queue AND ready.priority = batch.priority AND ready.enqueue_shard = batch.enqueue_shard AND ready.lane_seq = item.lane_seq AND ready.job_id = item.job_id WHERE NOT EXISTS ( SELECT 1 FROM %1$I.receipt_completion_tombstones AS tomb WHERE tomb.ready_slot = batch.ready_slot AND tomb.ready_generation = batch.ready_generation AND tomb.job_id = item.job_id AND tomb.run_lease = item.run_lease ) $ddl$, p_schema ); END; $job_output$; REVOKE EXECUTE ON FUNCTION awa.install_queue_storage_job_output(TEXT) FROM PUBLIC; -- Installs p_schema.ensure_claim_batch_job_index(p_slot), which adds the GIN -- index on job_ids to one lease_claim_batches partition when that partition -- is empty and its lock is free, and otherwise does nothing. Building the -- index on a populated partition holds SHARE, which blocks claim inserts, for -- the whole build (minutes per million batches), so the index is only ever -- created on an empty partition: by the installer, or by claim prune right -- after it truncates a slot. A different relation that already has the -- index's name is never dropped: the function warns, naming it, and the slot -- keeps scanning until an operator removes or renames it. -- -- fastupdate is off: job ids arrive in ascending order, so direct inserts -- append to the right edge of the entry tree and cost no more than the -- pending list does, while a pending list would make every lookup read it -- (up to gin_pending_list_limit) and push its flush into a claim insert. -- -- The function is SECURITY DEFINER, owned by the owner of lease_claim_batches -- (CREATE INDEX needs table ownership), with a pinned search_path. EXECUTE -- goes to the roles that may TRUNCATE lease_claim_batches, which are the roles -- that run claim prune, rather than to PUBLIC. Replacing it takes no table -- locks and reads no rows. The installer calls this too. CREATE OR REPLACE FUNCTION awa.refresh_claim_batch_job_index_helper(p_schema TEXT) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $refresh$ DECLARE v_table_owner OID; v_table_acl ACLITEM[]; v_function REGPROCEDURE; v_function_owner OID; v_grantee TEXT; v_previous_role TEXT; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; BEGIN IF p_schema IS NULL OR p_schema !~ '^[a-z_][a-z0-9_]*$' THEN RAISE EXCEPTION 'refresh_claim_batch_job_index_helper: schema name must match ^[a-z_][a-z0-9_]*$; got %', p_schema USING ERRCODE = '22023'; END IF; SELECT batches.relowner, batches.relacl INTO v_table_owner, v_table_acl FROM pg_class AS batches WHERE batches.oid = to_regclass(format('%I.lease_claim_batches', p_schema)); IF v_table_owner IS NULL THEN RAISE EXCEPTION 'refresh_claim_batch_job_index_helper: schema % has no lease_claim_batches table', p_schema USING ERRCODE = '22023'; END IF; EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.ensure_claim_batch_job_index(p_slot INTEGER) RETURNS BOOLEAN LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp SET quote_all_identifiers = off AS $func$ DECLARE v_child TEXT; v_index TEXT; v_has_rows BOOLEAN; BEGIN IF p_slot IS NULL OR p_slot < 0 THEN RAISE EXCEPTION 'invalid claim slot: %%', p_slot USING ERRCODE = '22023'; END IF; v_child := format('lease_claim_batches_%%s', p_slot); v_index := format('lease_claim_batches_%%s_job_ids_idx', p_slot); IF NOT EXISTS ( SELECT 1 FROM pg_inherits AS inheritance WHERE inheritance.inhparent = to_regclass(format('%%I.lease_claim_batches', %1$L)) AND inheritance.inhrelid = to_regclass(format('%%I.%%I', %1$L, v_child)) ) THEN RAISE EXCEPTION 'schema %% has no lease_claim_batches partition for claim slot %%', %1$L, p_slot USING ERRCODE = '22023'; END IF; -- Only a valid, non-partial GIN index on job_ids alone, with the -- default array_ops opclass, serves the by-job lookups. IF EXISTS ( SELECT 1 FROM pg_index AS idx JOIN pg_class AS index_class ON index_class.oid = idx.indexrelid JOIN pg_am AS method ON method.oid = index_class.relam JOIN pg_attribute AS job_ids ON job_ids.attrelid = idx.indrelid AND job_ids.attname = 'job_ids' AND NOT job_ids.attisdropped JOIN pg_opclass AS opclass ON opclass.oid = idx.indclass[0] WHERE idx.indrelid = to_regclass(format('%%I.%%I', %1$L, v_child)) AND method.amname = 'gin' AND idx.indisvalid AND idx.indpred IS NULL AND idx.indexprs IS NULL AND idx.indnatts = 1 AND idx.indkey[0] = job_ids.attnum AND opclass.opcname = 'array_ops' AND opclass.opcnamespace = 'pg_catalog'::regnamespace ) THEN RETURN TRUE; END IF; -- Something else already has the index's name: a partial or -- otherwise different index, or another relation. Leave it alone -- and keep scanning; the operator decides what to do with it. IF to_regclass(format('%%I.%%I', %1$L, v_index)) IS NOT NULL THEN RAISE WARNING '%%.%% is not a GIN index on job_ids, so claim slot %% of schema %% keeps scanning for job ids', quote_ident(%1$L), quote_ident(v_index), p_slot, %1$L USING HINT = format( 'Drop or rename %%s.%%s; claim prune builds the job_ids index the next time it empties claim slot %%s.', quote_ident(%1$L), quote_ident(v_index), p_slot ); RETURN FALSE; END IF; -- NOWAIT: a partition someone is writing to is not empty for long -- enough to index, so give up rather than queue behind claims. -- Leaving the block through the exception rolls back its -- subtransaction, which releases a lock taken here on a populated -- partition; a lock the caller already held is kept. BEGIN EXECUTE format('LOCK TABLE %%I.%%I IN SHARE MODE NOWAIT', %1$L, v_child); EXECUTE format('SELECT EXISTS (SELECT 1 FROM %%I.%%I)', %1$L, v_child) INTO v_has_rows; IF v_has_rows THEN RAISE EXCEPTION USING ERRCODE = 'object_not_in_prerequisite_state'; END IF; EXECUTE format( 'CREATE INDEX %%I ON %%I.%%I USING GIN (job_ids) WITH (fastupdate = off)', v_index, %1$L, v_child ); EXCEPTION WHEN lock_not_available OR object_not_in_prerequisite_state OR duplicate_table THEN RETURN FALSE; END; RETURN TRUE; END; $func$ $ddl$, p_schema ); v_function := format('%I.ensure_claim_batch_job_index(integer)', p_schema)::regprocedure; SELECT routine.proowner INTO v_function_owner FROM pg_proc AS routine WHERE routine.oid = v_function; IF v_function_owner <> v_table_owner THEN IF pg_has_role(current_user, v_function_owner, 'USAGE') AND pg_has_role(current_user, v_table_owner, v_set_mode) AND has_schema_privilege(v_table_owner, to_regnamespace(quote_ident(p_schema)), 'CREATE') THEN EXECUTE format( 'ALTER FUNCTION %s OWNER TO %I', v_function, pg_get_userbyid(v_table_owner) ); v_function_owner := v_table_owner; ELSE RAISE WARNING '% is owned by %, not the owner % of %.lease_claim_batches, so it cannot create the job_ids index', v_function, pg_get_userbyid(v_function_owner), pg_get_userbyid(v_table_owner), p_schema USING HINT = format( 'Run awa migrate as a role that can SET ROLE to %s, or as %s itself.', quote_ident(pg_get_userbyid(v_table_owner)), quote_ident(pg_get_userbyid(v_table_owner)) ); END IF; END IF; -- Reset EXECUTE as the function's owner, after any transfer, so a former -- owner that holds TRUNCATE keeps it. A role that may only SET ROLE to the -- new owner cannot grant or revoke as itself, so it acts as the owner for -- the reset and then restores its previous role. IF NOT pg_has_role(current_user, v_function_owner, 'USAGE') THEN v_previous_role := current_setting('role'); PERFORM set_config('role', pg_get_userbyid(v_function_owner), true); END IF; FOR v_grantee IN SELECT DISTINCT CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(acl.grantee)) END FROM pg_proc AS routine CROSS JOIN LATERAL aclexplode(COALESCE(routine.proacl, acldefault('f', routine.proowner))) AS acl WHERE routine.oid = v_function AND acl.privilege_type = 'EXECUTE' AND acl.grantee <> routine.proowner LOOP EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %s', v_function, v_grantee); END LOOP; FOR v_grantee IN SELECT DISTINCT CASE WHEN acl.grantee = 0 THEN 'PUBLIC' ELSE quote_ident(pg_get_userbyid(acl.grantee)) END FROM aclexplode(COALESCE(v_table_acl, acldefault('r', v_table_owner))) AS acl WHERE acl.privilege_type = 'TRUNCATE' LOOP EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO %s', v_function, v_grantee); END LOOP; IF v_previous_role IS NOT NULL THEN PERFORM set_config('role', v_previous_role, true); END IF; END; $refresh$; REVOKE EXECUTE ON FUNCTION awa.refresh_claim_batch_job_index_helper(TEXT) FROM PUBLIC; -- The queue-ring generation floor (#847). A producer reserves its lane -- positions under the lane's reservation lock and then reads the queue-ring -- cursor. Under REPEATABLE READ or SERIALIZABLE the cursor comes from a -- snapshot taken before the lock wait, so a later lane position could land in -- an older generation than an earlier one. Claims scan one (slot, generation) -- segment at a time and would move the lane's claim cursor past it. -- -- .queue_ring_generation_floor is a sequence whose last value is the -- newest queue-ring generation some transaction has read as committed. -- Reading a sequence ignores the reader's snapshot. .enqueue_ring_cursor() -- raises the floor to the generation its caller can see and returns the newer -- of the two. Producers call it while holding their lane locks, so every -- earlier enqueue in a lane raised the floor to its own generation before it -- committed, and generations never go backwards in a lane. The rotator calls -- it after committing a rotation, so a producer whose snapshot predates many -- rotations still writes into the current generation rather than a slot the -- ring has reused. The floor only ever holds a generation that was committed, -- whose slot rotation has prepared, and it only moves forward (except through -- QueueStorage::reset, which restarts the ring). -- -- enqueue_ring_cursor() is SECURITY DEFINER, owned by the owner of -- queue_ring_state, with a pinned search_path and every table it reads -- schema-qualified, and it calls no function that resolves names through a -- search_path of its own. PUBLIC may execute it: it -- returns the cursor and can raise the floor only to a generation the caller -- can already see, so no runtime role needs a new grant. If its owner cannot -- read the ring (the migration role could not hand it to the ring's owner), -- it is dropped again, with a warning, and producers keep reading the cursor -- directly. -- The helper seeds the floor from the committed cursor. Replacing the function -- takes no table locks. The installer calls this too. CREATE OR REPLACE FUNCTION awa.refresh_ring_generation_floor_helper(p_schema TEXT) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $refresh$ DECLARE v_owner OID; v_sequence REGCLASS; v_function REGPROCEDURE; v_object_owner OID; v_previous_role TEXT; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; BEGIN IF p_schema IS NULL OR p_schema !~ '^[a-z_][a-z0-9_]*$' THEN RAISE EXCEPTION 'refresh_ring_generation_floor_helper: schema name must match ^[a-z_][a-z0-9_]*$; got %', p_schema USING ERRCODE = '22023'; END IF; SELECT state.relowner INTO v_owner FROM pg_class AS state WHERE state.oid = to_regclass(format('%I.queue_ring_state', p_schema)); IF v_owner IS NULL OR to_regprocedure(format('%I.ring_cursor(text)', p_schema)) IS NULL THEN RAISE EXCEPTION 'refresh_ring_generation_floor_helper: schema % has no queue ring', p_schema USING ERRCODE = '22023'; END IF; -- A floor left from an earlier run that could not hand it over (the -- function was then left out) goes to the ring's owner first, while this -- role still holds the privileges of the sequence's owner. v_sequence := to_regclass(format('%I.queue_ring_generation_floor', p_schema)); IF v_sequence IS NOT NULL THEN SELECT seq.relowner INTO v_object_owner FROM pg_class AS seq WHERE seq.oid = v_sequence; IF v_object_owner <> v_owner AND pg_has_role(current_user, v_object_owner, 'USAGE') AND pg_has_role(current_user, v_owner, v_set_mode) AND has_schema_privilege(v_owner, to_regnamespace(quote_ident(p_schema)), 'CREATE') THEN EXECUTE format('ALTER SEQUENCE %s OWNER TO %I', v_sequence, pg_get_userbyid(v_owner)); END IF; END IF; -- Create, replace and grant as the ring's owner when the migration role -- may SET ROLE to it, so a migrator that does not inherit the owner's -- privileges (PostgreSQL 16+ INHERIT FALSE membership) can create in the -- schema and replace the function on a replay, and the objects belong to -- the owner from the start. IF v_owner <> (SELECT oid FROM pg_roles WHERE rolname = current_user) AND pg_has_role(current_user, v_owner, v_set_mode) AND has_schema_privilege(v_owner, to_regnamespace(quote_ident(p_schema)), 'CREATE') AND COALESCE( (SELECT routine.proowner FROM pg_proc AS routine WHERE routine.oid = to_regprocedure(format('%I.enqueue_ring_cursor()', p_schema))), v_owner ) = v_owner THEN v_previous_role := current_setting('role'); PERFORM set_config('role', pg_get_userbyid(v_owner), true); END IF; EXECUTE format( 'CREATE SEQUENCE IF NOT EXISTS %I.queue_ring_generation_floor AS BIGINT MINVALUE 0 START WITH 0', p_schema ); v_sequence := format('%I.queue_ring_generation_floor', p_schema)::regclass; EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.enqueue_ring_cursor() RETURNS TABLE(slot INT, generation BIGINT) LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $func$ DECLARE v_authority TEXT; v_slot INT; v_generation BIGINT; v_floor BIGINT; v_lock_key BIGINT := hashtextextended(%3$L, 0); BEGIN -- The same read as ring_cursor('queue'), done here rather than -- through it. This function runs as the ring's owner for any -- caller, so nothing it runs may resolve a name through a -- search_path: a caller's temporary objects would answer for an -- unqualified name in a function whose search_path leaves pg_temp -- out, and that function would run them as the owner. SELECT a.authority INTO v_authority FROM %1$I.ring_cursor_authority AS a WHERE a.singleton; IF v_authority = 'ledger' THEN SELECT rotation.slot, rotation.generation INTO v_slot, v_generation FROM %1$I.queue_ring_rotations AS rotation ORDER BY rotation.generation DESC LIMIT 1; ELSE SELECT state.current_slot, state.generation INTO v_slot, v_generation FROM %1$I.queue_ring_state AS state WHERE state.singleton; END IF; -- NULL until the first raise after creation or a reset. v_floor := pg_sequence_last_value(%2$L::regclass); IF v_floor IS NULL OR v_floor < v_generation THEN -- setval is not a compare-and-set, so raise under a short -- session lock, released before returning rather than at the -- end of the caller's transaction. Only the first producer to -- see each rotation gets here. A pooled connection would keep a -- leaked session lock, so every way out releases it, including -- a cancel or statement timeout, which OTHERS does not catch; -- the handler checks pg_locks because the error may have come -- before the lock was granted. BEGIN PERFORM pg_advisory_lock(v_lock_key); v_floor := pg_sequence_last_value(%2$L::regclass); IF v_floor IS NULL OR v_floor < v_generation THEN PERFORM setval(%2$L::regclass, v_generation, true); v_floor := v_generation; END IF; PERFORM pg_advisory_unlock(v_lock_key); EXCEPTION WHEN OTHERS OR query_canceled THEN IF EXISTS ( SELECT 1 FROM pg_catalog.pg_locks AS held WHERE held.locktype = 'advisory' AND held.pid = pg_backend_pid() AND held.granted AND held.objsubid = 1 AND held.classid = ((v_lock_key >> 32) & 4294967295)::oid AND held.objid = (v_lock_key & 4294967295)::oid ) THEN PERFORM pg_advisory_unlock(v_lock_key); END IF; RAISE; END; END IF; IF v_floor > v_generation THEN -- Rotation advances slot and generation together from (0, 0) -- and slot_count changes only when reset restarts the ring, -- so the floor's slot is its generation modulo slot_count. SELECT (v_floor %% state.slot_count)::int INTO v_slot FROM %1$I.queue_ring_state AS state WHERE state.singleton; v_generation := v_floor; END IF; slot := v_slot; generation := v_generation; RETURN NEXT; END; $func$ $ddl$, p_schema, format('%I.queue_ring_generation_floor', p_schema), format('awa.queue_storage.ring_generation_floor:%s', p_schema) ); v_function := format('%I.enqueue_ring_cursor()', p_schema)::regprocedure; -- The function reads and sets the floor with its owner's privileges, so -- the floor and the function belong to the queue ring's owner. SELECT seq.relowner INTO v_object_owner FROM pg_class AS seq WHERE seq.oid = v_sequence; IF v_object_owner <> v_owner THEN IF pg_has_role(current_user, v_object_owner, 'USAGE') AND pg_has_role(current_user, v_owner, v_set_mode) AND has_schema_privilege(v_owner, to_regnamespace(quote_ident(p_schema)), 'CREATE') THEN EXECUTE format('ALTER SEQUENCE %s OWNER TO %I', v_sequence, pg_get_userbyid(v_owner)); ELSE RAISE WARNING '% is owned by %, not the owner % of %.queue_ring_state', v_sequence, pg_get_userbyid(v_object_owner), pg_get_userbyid(v_owner), p_schema USING HINT = format( 'Run awa migrate as a role that can SET ROLE to %s, or as %s itself.', quote_ident(pg_get_userbyid(v_owner)), quote_ident(pg_get_userbyid(v_owner)) ); END IF; END IF; SELECT routine.proowner INTO v_object_owner FROM pg_proc AS routine WHERE routine.oid = v_function; IF v_object_owner <> v_owner THEN IF pg_has_role(current_user, v_object_owner, 'USAGE') AND pg_has_role(current_user, v_owner, v_set_mode) AND has_schema_privilege(v_owner, to_regnamespace(quote_ident(p_schema)), 'CREATE') THEN EXECUTE format('ALTER FUNCTION %s OWNER TO %I', v_function, pg_get_userbyid(v_owner)); v_object_owner := v_owner; ELSE RAISE WARNING '% is owned by %, not the owner % of %.queue_ring_state', v_function, pg_get_userbyid(v_object_owner), pg_get_userbyid(v_owner), p_schema USING HINT = format( 'Run awa migrate as a role that can SET ROLE to %s, or as %s itself.', quote_ident(pg_get_userbyid(v_owner)), quote_ident(pg_get_userbyid(v_owner)) ); END IF; END IF; -- The function runs as its owner, so its owner must be able to read the -- ring and the floor. If it cannot (the transfer above was not possible), -- the function is dropped: producers then read the cursor as they did -- before the floor existed, instead of failing. IF has_table_privilege(v_object_owner, format('%I.ring_cursor_authority', p_schema), 'SELECT') AND has_table_privilege(v_object_owner, format('%I.queue_ring_rotations', p_schema), 'SELECT') AND has_table_privilege(v_object_owner, format('%I.queue_ring_state', p_schema), 'SELECT') AND has_sequence_privilege(v_object_owner, v_sequence, 'SELECT') AND has_sequence_privilege(v_object_owner, v_sequence, 'UPDATE') THEN -- New functions are executable by PUBLIC already; this restores it -- should anything have revoked it. EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO PUBLIC', v_function); -- Seed the floor from the committed cursor. EXECUTE format('SELECT FROM %I.enqueue_ring_cursor()', p_schema); ELSE EXECUTE format('DROP FUNCTION %s', v_function); RAISE WARNING '% cannot read the queue ring of schema %, so enqueues there keep writing without the generation floor (#847)', pg_get_userbyid(v_object_owner), p_schema USING HINT = format( 'Run awa migrate as a role that can SET ROLE to %s, or as %s itself.', quote_ident(pg_get_userbyid(v_owner)), quote_ident(pg_get_userbyid(v_owner)) ); END IF; IF v_previous_role IS NOT NULL THEN PERFORM set_config('role', v_previous_role, true); END IF; END; $refresh$; REVOKE EXECUTE ON FUNCTION awa.refresh_ring_generation_floor_helper(TEXT) FROM PUBLIC; -- Every function in awa and in a queue-storage schema that sets its own -- search_path lists pg_temp last and leaves public out. A search_path that -- leaves pg_temp out searches the session's temporary schema first for -- tables, so when such a function runs with its owner's privileges, below a -- SECURITY DEFINER function or a trigger, a caller's temporary table or view -- can answer for an unqualified name. public, where a database lets roles -- create in it, would let them plant functions the same way. Functions that -- set no search_path inherit their caller's, which under a definer is the -- definer's pinned one. -- -- Older migrations and the installer write the paths they always have; this -- rewrites them in place, so it runs at the end of the installer and after -- each migration step that refreshes these helpers. Each ALTER runs as the -- function's owner, by SET ROLE when the current role may only do that; a -- function whose owner the current role can neither act as nor become is -- left as it is with a warning. Altering a function takes no table locks, and -- a function already pinned is not touched. CREATE OR REPLACE FUNCTION awa.pin_function_search_paths(p_schema TEXT) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $pin$ DECLARE v_routine RECORD; v_entries TEXT[]; v_entry TEXT; v_path TEXT[]; v_previous_role TEXT; v_lent_usage BOOLEAN; v_set_mode TEXT := CASE WHEN current_setting('server_version_num')::int >= 160000 THEN 'SET' ELSE 'MEMBER' END; BEGIN IF p_schema IS NULL OR p_schema !~ '^[a-z_][a-z0-9_]*$' THEN RAISE EXCEPTION 'pin_function_search_paths: schema name must match ^[a-z_][a-z0-9_]*$; got %', p_schema USING ERRCODE = '22023'; END IF; FOR v_routine IN SELECT routine.oid::regprocedure AS signature, routine.proowner AS owner, substr(setting, length('search_path=') + 1) AS search_path FROM pg_proc AS routine CROSS JOIN LATERAL unnest(routine.proconfig) AS setting WHERE routine.pronamespace = to_regnamespace(quote_ident(p_schema)) AND routine.prokind IN ('f', 'p') AND setting LIKE 'search_path=%' AND NOT EXISTS ( SELECT 1 FROM pg_depend AS dependency WHERE dependency.classid = 'pg_proc'::regclass AND dependency.objid = routine.oid AND dependency.deptype = 'e' ) ORDER BY routine.oid LOOP v_entries := regexp_split_to_array(btrim(v_routine.search_path), '[[:space:]]*,[[:space:]]*'); v_path := ARRAY[]::TEXT[]; FOREACH v_entry IN ARRAY v_entries LOOP IF v_entry !~ '^[a-z_][a-z0-9_]*$' THEN RAISE WARNING 'pin_function_search_paths: % has search_path entry %, which is not a plain schema name; left as it is', v_routine.signature, quote_literal(v_entry); v_path := NULL; EXIT; END IF; IF v_entry NOT IN ('public', 'pg_temp') THEN v_path := v_path || v_entry; END IF; END LOOP; IF v_path IS NULL THEN CONTINUE; END IF; v_path := v_path || 'pg_temp'::TEXT; IF v_entries = v_path THEN CONTINUE; END IF; -- One subtransaction per function, so a refusal also undoes the -- role switch and the lent USAGE. BEGIN v_previous_role := NULL; v_lent_usage := false; IF NOT pg_has_role(current_user, v_routine.owner, 'USAGE') THEN IF NOT pg_has_role(current_user, v_routine.owner, v_set_mode) THEN RAISE insufficient_privilege; END IF; -- The owner needs USAGE on the schema to name the function; -- a migrator that may only SET ROLE to it lends that for the -- ALTER, as awa.refresh_lane_sequence_helpers_as_migrator does. IF NOT has_schema_privilege(v_routine.owner, quote_ident(p_schema), 'USAGE') THEN EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', p_schema, pg_get_userbyid(v_routine.owner)); v_lent_usage := true; END IF; v_previous_role := current_setting('role'); PERFORM set_config('role', pg_get_userbyid(v_routine.owner), true); END IF; EXECUTE format( 'ALTER ROUTINE %s SET search_path = %s', v_routine.signature, array_to_string(v_path, ', ') ); IF v_previous_role IS NOT NULL THEN PERFORM set_config('role', v_previous_role, true); END IF; IF v_lent_usage THEN EXECUTE format('REVOKE USAGE ON SCHEMA %I FROM %I', p_schema, pg_get_userbyid(v_routine.owner)); END IF; EXCEPTION WHEN insufficient_privilege THEN RAISE WARNING 'could not pin the search_path of %, owned by %: %', v_routine.signature, pg_get_userbyid(v_routine.owner), SQLERRM USING HINT = format( 'Run SELECT awa.pin_function_search_paths(%L) as %s; that role needs USAGE on schema awa and on %I.', p_schema, quote_ident(pg_get_userbyid(v_routine.owner)), p_schema ); END; END LOOP; END; $pin$; REVOKE EXECUTE ON FUNCTION awa.pin_function_search_paths(TEXT) FROM PUBLIC; CREATE OR REPLACE FUNCTION awa.install_queue_storage_substrate( p_schema TEXT, p_queue_slot_count INT DEFAULT 16, p_lease_slot_count INT DEFAULT 8, p_claim_slot_count INT DEFAULT 8, p_lease_claim_receipts BOOLEAN DEFAULT TRUE ) RETURNS VOID LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, awa, public SET quote_all_identifiers = off AS $install$ DECLARE v_slot INT; v_ring TEXT; v_claimed_cte TEXT; v_claim_runtime REGPROCEDURE; v_identity_rel REGCLASS; v_claimer_owner_index REGCLASS; -- #371 staged rolling upgrade: was this a FRESH install (the ring -- state did not exist before this call) or an UPGRADE of an existing -- schema? A fresh install has no old binaries that could still read -- the compat columns, so it starts directly in ledger authority; an -- upgrade starts in columns authority and flips later once the fleet -- has fully rolled to 0.7. We probe the queue ring, which is present -- on every installed shape (0.6, the unreleased shipped-v043 dev -- shape, and fresh). v_fresh_install BOOLEAN; BEGIN IF p_schema IS NULL OR p_schema !~ '^[a-z_][a-z0-9_]*$' THEN RAISE EXCEPTION 'install_queue_storage_substrate: schema name must match ^[a-z_][a-z0-9_]*$; got %', p_schema USING ERRCODE = '22023'; END IF; IF p_queue_slot_count IS NULL OR p_queue_slot_count < 4 THEN RAISE EXCEPTION 'install_queue_storage_substrate: queue_slot_count must be >= 4; got %', p_queue_slot_count USING ERRCODE = '22023'; END IF; IF p_lease_slot_count IS NULL OR p_lease_slot_count < 2 THEN RAISE EXCEPTION 'install_queue_storage_substrate: lease_slot_count must be >= 2; got %', p_lease_slot_count USING ERRCODE = '22023'; END IF; IF p_claim_slot_count IS NULL OR p_claim_slot_count < 2 THEN RAISE EXCEPTION 'install_queue_storage_substrate: claim_slot_count must be >= 2; got %', p_claim_slot_count USING ERRCODE = '22023'; END IF; IF p_lease_claim_receipts IS NULL THEN RAISE EXCEPTION 'install_queue_storage_substrate: lease_claim_receipts must not be NULL' USING ERRCODE = '22023'; END IF; -- Serialize concurrent installs for the same schema. The lock name -- matches the Rust `prepare_schema()` lock, so a CLI install racing -- with a Rust worker boot serializes on the same key. PERFORM pg_advisory_xact_lock( hashtextextended(format('awa.queue_storage.install:%I', p_schema), 0) ); -- The default `awa` substrate is migration-owned. Reject non-default -- configuration with a clear hint directing the operator to a custom -- queue-storage schema. IF p_schema = 'awa' THEN IF p_lease_claim_receipts IS NOT TRUE THEN RAISE EXCEPTION 'install_queue_storage_substrate: the default ''awa'' substrate requires lease_claim_receipts=TRUE' USING ERRCODE = '22023', HINT = 'Use a custom queue-storage schema if you need lease_claim_receipts=FALSE; the default awa schema is migration-owned and default-shaped.'; END IF; IF p_queue_slot_count <> 16 OR p_lease_slot_count <> 8 OR p_claim_slot_count <> 8 THEN RAISE EXCEPTION 'install_queue_storage_substrate: the default ''awa'' substrate must use the default slot counts (queue=16, lease=8, claim=8); got (queue=%, lease=%, claim=%)', p_queue_slot_count, p_lease_slot_count, p_claim_slot_count USING ERRCODE = '22023', HINT = 'Use a custom queue-storage schema if you need non-default slot counts; the default awa schema is migration-owned and default-shaped.'; END IF; END IF; EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I', p_schema); -- Job-id sequence. EXECUTE format('CREATE SEQUENCE IF NOT EXISTS %I.job_id_seq', p_schema); -------------------------------------------------------------------- -- Ring-state singletons (queue / lease / claim), rotation ledgers, -- and slot tables. -- -- #371 STAGED ROLLING UPGRADE. The ring cursor has two representations -- that coexist during a rolling upgrade, selected per schema by -- `{schema}.ring_cursor_authority`: -- -- * `columns` (compat) — the pre-0.7 mutable `{ring}_ring_state` -- `current_slot` / `generation` singleton columns are authoritative, -- exactly as 0.6 wrote them. 0.7 rotators additionally shadow every -- advance into the append-only `{ring}_ring_rotations` ledger, so -- the ledger is an eventually-consistent copy ready for the flip. -- * `ledger` — the current cursor is the max-generation row of the -- append-only ledger (backward PK scan, O(1)); the singleton columns -- go stale (a returning pre-ledger binary is fenced off — see the flip). -- -- This keeps the migration ADDITIVE: the compat columns are RESTORED, -- not dropped, so a mixed 0.6.2/0.7 fleet runs against one database. -- The one-way `columns -> ledger` flip -- (manual `awa storage flip-ring-authority` or the maintenance auto-flip -- once the fleet has fully rolled to 0.7) is what finally retires the -- columns; the 0.8 contract migration drops them. Fresh installs skip -- straight to `ledger` because no old binary can exist. -------------------------------------------------------------------- -- Fresh vs. upgrade: probe BEFORE the CREATE IF NOT EXISTS below. v_fresh_install := to_regclass(format('%I.queue_ring_state', p_schema)) IS NULL; EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_ring_state ( singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), slot_count INT NOT NULL ) $ddl$, p_schema ); -- #290: live-terminal-counter trust marker. See queue_storage.rs for -- the rationale. Added via ALTER + IF NOT EXISTS so the column is -- present on both fresh installs and upgrades. EXECUTE format( 'ALTER TABLE %I.queue_ring_state ADD COLUMN IF NOT EXISTS terminal_counter_trusted_at TIMESTAMPTZ', p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_ring_state SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_ring_rotations ( generation BIGINT PRIMARY KEY, slot INT NOT NULL, rotated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ) $ddl$, p_schema ); -- Compat columns are ADDITIVE (#371 staged upgrade). Restore the -- pre-0.7 mutable cursor columns if they are absent: -- * a 0.6 schema still HAS them (0.6 wrote them) — the ADD ... IF NOT -- EXISTS is a no-op and the live cursor is preserved as-is; -- * the unreleased shipped-v043 dev shape DROPPED them — re-ADD and -- re-seed from the ledger's max-generation row (the inverse of the -- original seed), so the current cursor survives either direction. EXECUTE format( $ddl$ ALTER TABLE %I.queue_ring_state ADD COLUMN IF NOT EXISTS current_slot INT, ADD COLUMN IF NOT EXISTS generation BIGINT $ddl$, p_schema ); -- Seed the singleton with a genesis cursor (0, 0). ON CONFLICT DO -- NOTHING preserves an existing 0.6 cursor. Providing current_slot / -- generation here satisfies the NOT NULL constraint a 0.6 schema still -- carries on those columns (the restored columns are nullable on the -- dev-shape path, where the reconcile UPDATE below fills them instead). EXECUTE format( 'INSERT INTO %I.queue_ring_state (singleton, slot_count, current_slot, generation) VALUES (TRUE, %s, 0, 0) ON CONFLICT (singleton) DO NOTHING', p_schema, p_queue_slot_count ); -- Genesis cursor for fresh installs: slot 0, generation 0. Runs before -- the seed reconciliation below so a fresh ledger has its genesis row. EXECUTE format( 'INSERT INTO %1$I.queue_ring_rotations (generation, slot) SELECT 0, 0 WHERE NOT EXISTS (SELECT 1 FROM %1$I.queue_ring_rotations)', p_schema ); -- Reconcile the two representations so BOTH agree on the current -- cursor before any rotator runs, regardless of which one arrived -- populated: -- * columns NULL (fresh, or the dev-shape v043 that dropped them) -> -- seed columns from the ledger's max-generation row (genesis 0/0 on -- a fresh install); -- * columns populated but the ledger is behind (0.6 upgrade — the -- ledger was just created empty except for genesis) -> append the -- column cursor as the ledger's current row. Only the current row -- is needed: the ledger fold trims to one wrap anyway, and sealed- -- slot enumeration derives older generations arithmetically -- (`slot = generation mod slot_count`). EXECUTE format( $ddl$ UPDATE %1$I.queue_ring_state AS s SET current_slot = ledger.slot, generation = ledger.generation FROM ( SELECT slot, generation FROM %1$I.queue_ring_rotations ORDER BY generation DESC LIMIT 1 ) AS ledger WHERE s.singleton AND s.current_slot IS NULL $ddl$, p_schema ); EXECUTE format( $ddl$ INSERT INTO %1$I.queue_ring_rotations (generation, slot) SELECT s.generation, s.current_slot FROM %1$I.queue_ring_state AS s WHERE s.singleton AND s.generation >= 0 ON CONFLICT (generation) DO NOTHING $ddl$, p_schema ); -- Under ledger authority the columns hold the (-1, -1) fence, which is -- not a cursor: the copy above skips it, and any negative-generation -- row already in the ledger is removed. EXECUTE format( 'DELETE FROM %I.queue_ring_rotations WHERE generation < 0', p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_ring_slots ( slot INT PRIMARY KEY ) $ddl$, p_schema ); -- #371 staged upgrade: the per-slot `generation` column is ADDITIVE. -- In ledger authority it is derived from the cursor (`slot = generation -- mod slot_count`; rotation advances both in lock-step) and left -- untouched, but a 0.6 rotator in a mixed fleet still UPDATEs it on -- every advance, so it must exist. Restore it (no-op on a 0.6 schema -- that never dropped it; re-seed to the derived value on the dev-shape -- v043 that dropped it). NOT NULL DEFAULT -1 matches the pre-0.7 shape: -- -1 means "never rotated through". EXECUTE format( 'ALTER TABLE %I.queue_ring_slots ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT -1', p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_ring_slots SET ( fillfactor = 70, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_ring_state ( singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), slot_count INT NOT NULL ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.lease_ring_state SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_ring_rotations ( generation BIGINT PRIMARY KEY, slot INT NOT NULL, rotated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ) $ddl$, p_schema ); -- Compat columns are additive; restore + reconcile against the ledger -- (see the queue-ring block above for the full rationale). EXECUTE format( $ddl$ ALTER TABLE %I.lease_ring_state ADD COLUMN IF NOT EXISTS current_slot INT, ADD COLUMN IF NOT EXISTS generation BIGINT $ddl$, p_schema ); EXECUTE format( 'INSERT INTO %I.lease_ring_state (singleton, slot_count, current_slot, generation) VALUES (TRUE, %s, 0, 0) ON CONFLICT (singleton) DO NOTHING', p_schema, p_lease_slot_count ); EXECUTE format( 'INSERT INTO %1$I.lease_ring_rotations (generation, slot) SELECT 0, 0 WHERE NOT EXISTS (SELECT 1 FROM %1$I.lease_ring_rotations)', p_schema ); EXECUTE format( $ddl$ UPDATE %1$I.lease_ring_state AS s SET current_slot = ledger.slot, generation = ledger.generation FROM ( SELECT slot, generation FROM %1$I.lease_ring_rotations ORDER BY generation DESC LIMIT 1 ) AS ledger WHERE s.singleton AND s.current_slot IS NULL $ddl$, p_schema ); EXECUTE format( $ddl$ INSERT INTO %1$I.lease_ring_rotations (generation, slot) SELECT s.generation, s.current_slot FROM %1$I.lease_ring_state AS s WHERE s.singleton AND s.generation >= 0 ON CONFLICT (generation) DO NOTHING $ddl$, p_schema ); -- Under ledger authority the columns hold the (-1, -1) fence, which is -- not a cursor: the copy above skips it, and any negative-generation -- row already in the ledger is removed. EXECUTE format( 'DELETE FROM %I.lease_ring_rotations WHERE generation < 0', p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_ring_slots ( slot INT PRIMARY KEY ) $ddl$, p_schema ); -- Per-slot generation is additive (compat rotators still write it). EXECUTE format( 'ALTER TABLE %I.lease_ring_slots ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT -1', p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.lease_ring_slots SET ( fillfactor = 70, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); -- ADR-023 claim-ring control plane. EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.claim_ring_state ( singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), slot_count INT NOT NULL ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.claim_ring_state SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.claim_ring_rotations ( generation BIGINT PRIMARY KEY, slot INT NOT NULL, rotated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ) $ddl$, p_schema ); -- Compat columns are additive; restore + reconcile against the ledger -- (see the queue-ring block above for the full rationale). EXECUTE format( $ddl$ ALTER TABLE %I.claim_ring_state ADD COLUMN IF NOT EXISTS current_slot INT, ADD COLUMN IF NOT EXISTS generation BIGINT $ddl$, p_schema ); EXECUTE format( 'INSERT INTO %I.claim_ring_state (singleton, slot_count, current_slot, generation) VALUES (TRUE, %s, 0, 0) ON CONFLICT (singleton) DO NOTHING', p_schema, p_claim_slot_count ); EXECUTE format( 'INSERT INTO %1$I.claim_ring_rotations (generation, slot) SELECT 0, 0 WHERE NOT EXISTS (SELECT 1 FROM %1$I.claim_ring_rotations)', p_schema ); EXECUTE format( $ddl$ UPDATE %1$I.claim_ring_state AS s SET current_slot = ledger.slot, generation = ledger.generation FROM ( SELECT slot, generation FROM %1$I.claim_ring_rotations ORDER BY generation DESC LIMIT 1 ) AS ledger WHERE s.singleton AND s.current_slot IS NULL $ddl$, p_schema ); EXECUTE format( $ddl$ INSERT INTO %1$I.claim_ring_rotations (generation, slot) SELECT s.generation, s.current_slot FROM %1$I.claim_ring_state AS s WHERE s.singleton AND s.generation >= 0 ON CONFLICT (generation) DO NOTHING $ddl$, p_schema ); -- Under ledger authority the columns hold the (-1, -1) fence, which is -- not a cursor: the copy above skips it, and any negative-generation -- row already in the ledger is removed. EXECUTE format( 'DELETE FROM %I.claim_ring_rotations WHERE generation < 0', p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.claim_ring_slots ( slot INT PRIMARY KEY, rescue_cursor_claimed_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, rescue_cursor_job_id BIGINT NOT NULL DEFAULT 0, rescue_cursor_run_lease BIGINT NOT NULL DEFAULT 0, deadline_cursor_deadline_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, deadline_cursor_job_id BIGINT NOT NULL DEFAULT 0, deadline_cursor_run_lease BIGINT NOT NULL DEFAULT 0, batch_deadline_cursor_deadline_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, batch_deadline_cursor_batch_id BIGINT NOT NULL DEFAULT 0 ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.claim_ring_slots ADD COLUMN IF NOT EXISTS rescue_cursor_claimed_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, ADD COLUMN IF NOT EXISTS rescue_cursor_job_id BIGINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS rescue_cursor_run_lease BIGINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS deadline_cursor_deadline_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, ADD COLUMN IF NOT EXISTS deadline_cursor_job_id BIGINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS deadline_cursor_run_lease BIGINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS batch_deadline_cursor_deadline_at TIMESTAMPTZ NOT NULL DEFAULT '-infinity'::timestamptz, ADD COLUMN IF NOT EXISTS batch_deadline_cursor_batch_id BIGINT NOT NULL DEFAULT 0 $ddl$, p_schema ); -- Per-slot generation is additive (compat rotators still write it). EXECUTE format( 'ALTER TABLE %I.claim_ring_slots ADD COLUMN IF NOT EXISTS generation BIGINT NOT NULL DEFAULT -1', p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.rescue_cursor_claimed_at IS 'Receipt-rescue sweep cursor: claimed_at component of the last claim visited in this slot; stale unclosed claims stop advancement until rescue closes them, and fresh claims are revisited after wrap.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.rescue_cursor_job_id IS 'Receipt-rescue sweep cursor tie-breaker: job_id component of the last claim visited in this slot.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.rescue_cursor_run_lease IS 'Receipt-rescue sweep cursor tie-breaker: run_lease component of the last claim visited in this slot.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.deadline_cursor_deadline_at IS 'Receipt deadline-rescue sweep cursor: deadline_at component of the last deadline claim visited in this slot; open future deadlines stop advancement until they expire or close.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.deadline_cursor_job_id IS 'Receipt deadline-rescue sweep cursor tie-breaker: job_id component of the last deadline claim visited in this slot.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.deadline_cursor_run_lease IS 'Receipt deadline-rescue sweep cursor tie-breaker: run_lease component of the last deadline claim visited in this slot.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.batch_deadline_cursor_deadline_at IS 'Compact-batch deadline-rescue sweep cursor (#246): deadline_at component of the last expired lease_claim_batches row visited in this slot; a batch with any open expired member stops advancement until rescue or completion closes it.' $ddl$, p_schema ); EXECUTE format( $ddl$ COMMENT ON COLUMN %I.claim_ring_slots.batch_deadline_cursor_batch_id IS 'Compact-batch deadline-rescue sweep cursor tie-breaker: batch_id component of the last expired claim batch visited in this slot.' $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.claim_ring_slots SET ( fillfactor = 70, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); -------------------------------------------------------------------- -- Ring-cursor authority control (#371 staged rolling upgrade). -- -- One row per queue-storage schema selecting which representation of -- the ring cursor is authoritative for every ring in this schema: -- 'columns' — the pre-0.7 `{ring}_ring_state` singleton columns -- (compat; a mixed 0.6.2/0.7 fleet is safe); -- 'ledger' — the append-only `{ring}_ring_rotations` ledgers -- (#371 dead-tuple-free rotation). -- The flip is one-way (columns -> ledger); the CHECK constraint and the -- `awa.flip_ring_authority()` function enforce it. Follows the -- `awa.storage_transition_state` house pattern: a tiny control row that -- state-transition SQL advances, wrapped by Rust. -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.ring_cursor_authority ( singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton), authority TEXT NOT NULL CHECK (authority IN ('columns', 'ledger')), flipped_at TIMESTAMPTZ ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.ring_cursor_authority SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 50 ) $ddl$, p_schema ); -- Seed the authority. A FRESH install (the ring state did not exist -- before this call) has no old binaries that could read the compat -- columns, so it starts directly in ledger authority; an UPGRADE of an -- existing schema (0.6, or the unreleased shipped-v043 dev shape) -- starts in columns authority and flips later once the fleet has fully -- rolled to 0.7. ON CONFLICT DO NOTHING preserves an already-flipped -- authority across a re-run of the installer (idempotent, one-way). EXECUTE format( 'INSERT INTO %I.ring_cursor_authority (singleton, authority, flipped_at) VALUES (TRUE, %L, %s) ON CONFLICT (singleton) DO NOTHING', p_schema, CASE WHEN v_fresh_install THEN 'ledger' ELSE 'columns' END, CASE WHEN v_fresh_install THEN 'now()' ELSE 'NULL' END ); -- A fresh ledger-authority install has no compat window. Poison the -- legacy cursor immediately so a pre-ledger binary cannot attach later -- and silently route through the stale singleton columns. Upgrade -- installs remain in `columns` authority and retain their live cursor. IF v_fresh_install THEN EXECUTE format( 'UPDATE %I.queue_ring_state SET current_slot = -1, generation = -1 WHERE singleton', p_schema ); EXECUTE format( 'UPDATE %I.lease_ring_state SET current_slot = -1, generation = -1 WHERE singleton', p_schema ); EXECUTE format( 'UPDATE %I.claim_ring_state SET current_slot = -1, generation = -1 WHERE singleton', p_schema ); END IF; -- Database-enforced post-flip fence. A pre-ledger rotator computes slot -- zero from the -1 sentinel, so the sentinel alone is not a fence. This -- trigger rejects any old-style cursor advance once ledger authority is -- active. Current code only locks these rows in ledger mode; unrelated -- cold metadata updates on queue_ring_state remain allowed. EXECUTE format( $fn$ CREATE OR REPLACE FUNCTION %1$I.reject_compat_ring_cursor_update_after_flip() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path = pg_catalog, %1$I, public AS $body$ DECLARE v_ledger_authority BOOLEAN := FALSE; BEGIN IF to_regclass(format('%%I.ring_cursor_authority', TG_TABLE_SCHEMA)) IS NOT NULL THEN EXECUTE format( 'SELECT EXISTS (SELECT 1 FROM %%I.ring_cursor_authority WHERE singleton AND authority = ''ledger'')', TG_TABLE_SCHEMA ) INTO v_ledger_authority; END IF; IF (NEW.current_slot, NEW.generation) IS DISTINCT FROM (OLD.current_slot, OLD.generation) AND v_ledger_authority THEN RAISE EXCEPTION 'pre-ledger ring cursor update rejected after ledger-authority flip' USING ERRCODE = '55000'; END IF; RETURN NEW; END; $body$ $fn$, p_schema ); FOR v_ring IN SELECT unnest(ARRAY['queue', 'lease', 'claim']) LOOP EXECUTE format( 'DROP TRIGGER IF EXISTS reject_compat_ring_cursor_update_after_flip ON %I.%I_ring_state', p_schema, v_ring ); EXECUTE format( 'CREATE TRIGGER reject_compat_ring_cursor_update_after_flip BEFORE UPDATE OF current_slot, generation ON %I.%I_ring_state FOR EACH ROW EXECUTE FUNCTION %I.reject_compat_ring_cursor_update_after_flip()', p_schema, v_ring, p_schema ); END LOOP; -- Per-schema current-cursor resolver honouring the authority. Every -- server-side read of a ring cursor (claim_ready_runtime, the SQL -- producer path insert_job_compat, etc.) goes through this one function -- so the columns/ledger branch lives in exactly one place. Callers wrap -- it in an `AS MATERIALIZED` CTE (loops=1); the function itself reads -- the single-row authority page plus one O(1) cursor read. -- The schema is baked into the function body as a quoted literal -- (`%1$L`) so the dynamic reads target this exact schema regardless of -- the caller's search_path (`current_schema()` here would resolve to -- pg_catalog, the first search_path entry). pg_temp is listed last: left -- out, it would be searched first for tables, and a temporary view named -- ring_cursor_authority would answer for the real one, running with the -- privileges of whichever role called this function. EXECUTE format( $fn$ CREATE OR REPLACE FUNCTION %1$I.ring_cursor(p_ring TEXT) RETURNS TABLE(slot INT, generation BIGINT) LANGUAGE plpgsql STABLE SECURITY INVOKER SET search_path = pg_catalog, %1$I, pg_temp AS $body$ DECLARE v_authority TEXT; BEGIN IF p_ring NOT IN ('queue', 'lease', 'claim') THEN RAISE EXCEPTION 'ring_cursor: unknown ring %%', p_ring USING ERRCODE = '22023'; END IF; SELECT a.authority INTO v_authority FROM %1$I.ring_cursor_authority AS a WHERE a.singleton; IF v_authority = 'ledger' THEN -- Max-generation row of the append-only ledger (backward PK -- scan, O(1)). RETURN QUERY EXECUTE format( 'SELECT slot, generation FROM %1$I.%%I ORDER BY generation DESC LIMIT 1', p_ring || '_ring_rotations' ); ELSE -- Compat: the pre-0.7 mutable singleton columns are -- authoritative (a live 0.6 rotator keeps them current). RETURN QUERY EXECUTE format( 'SELECT current_slot, generation FROM %1$I.%%I WHERE singleton', p_ring || '_ring_state' ); END IF; END; $body$ $fn$, p_schema ); EXECUTE format( 'REVOKE EXECUTE ON FUNCTION %I.ring_cursor(TEXT) FROM PUBLIC', p_schema ); -------------------------------------------------------------------- -- Lane / head tables. -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_lanes ( queue TEXT NOT NULL, priority SMALLINT NOT NULL, next_seq BIGINT NOT NULL DEFAULT 1, claim_seq BIGINT NOT NULL DEFAULT 1, pruned_completed_count BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (queue, priority) ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_enqueue_heads ( queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, next_seq BIGINT NOT NULL DEFAULT 1, seq_name TEXT, PRIMARY KEY (queue, priority, enqueue_shard) ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_enqueue_heads SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_claim_heads ( queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, claim_seq BIGINT NOT NULL DEFAULT 1, seq_name TEXT, PRIMARY KEY (queue, priority, enqueue_shard) ) $ddl$, p_schema ); IF to_regclass(format('%I.%I', p_schema, 'ready_segments')) IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM pg_partitioned_table WHERE partrelid = to_regclass(format('%I.%I', p_schema, 'ready_segments')) ) THEN IF to_regclass(format('%I.%I', p_schema, 'ready_segments_unpartitioned')) IS NOT NULL THEN RAISE EXCEPTION 'install_queue_storage_substrate: cannot convert %.ready_segments while %.ready_segments_unpartitioned already exists', p_schema, p_schema USING ERRCODE = '55000'; END IF; EXECUTE format( 'ALTER TABLE %I.ready_segments RENAME TO ready_segments_unpartitioned', p_schema ); EXECUTE format( 'ALTER TABLE %I.ready_segments_unpartitioned DROP CONSTRAINT IF EXISTS ready_segments_pkey', p_schema ); EXECUTE format( 'DROP INDEX IF EXISTS %I.%I', p_schema, format('idx_%s_ready_segments_lane_next', p_schema) ); EXECUTE format( 'DROP INDEX IF EXISTS %I.%I', p_schema, format('idx_%s_ready_segments_slot', p_schema) ); END IF; EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.ready_segments ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, first_lane_seq BIGINT NOT NULL, next_lane_seq BIGINT NOT NULL, first_run_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), CHECK (first_lane_seq < next_lane_seq), PRIMARY KEY (ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.ready_segments IS %L', p_schema, 'Append-only lane segment map from committed ready lane ranges to queue ring slot/generation. Claim uses this compact control plane to target a ready slot/generation before validating ready_entries; queue-ring prune truncates segment children with the matching ready slot.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_segments.first_lane_seq IS %L', p_schema, 'Inclusive first lane sequence covered by this committed ready segment.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_segments.next_lane_seq IS %L', p_schema, 'Exclusive upper lane sequence covered by this committed ready segment.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_segments.first_run_at IS %L', p_schema, 'run_at timestamp shared by rows in this segment; segment construction splits on run_at so claim-time priority aging remains exact as the claim cursor advances inside the segment.' ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_segments_lane_next ON %I.ready_segments (queue, priority, enqueue_shard, next_lane_seq, first_lane_seq)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_segments_slot ON %I.ready_segments (ready_slot, ready_generation)', p_schema, p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_enqueue_heads ADD COLUMN IF NOT EXISTS seq_name TEXT', p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_claim_heads ADD COLUMN IF NOT EXISTS seq_name TEXT', p_schema ); -- ready_segment_* are a legacy claim-routing cache. claim_ready_runtime no -- longer reads or writes them — it resolves the target ready slot from -- ready_segments on every claim — but they are retained UNUSED so workers -- still on the previous queue_storage_schema_ready check start cleanly -- during a rolling upgrade. Dropping them is a breaking change deferred to a -- major version per the additive-only migration policy (see migrations.rs). EXECUTE format( 'ALTER TABLE %I.queue_claim_heads ADD COLUMN IF NOT EXISTS ready_segment_slot INT', p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_claim_heads ADD COLUMN IF NOT EXISTS ready_segment_generation BIGINT', p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_claim_heads ADD COLUMN IF NOT EXISTS ready_segment_next_lane_seq BIGINT', p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_claim_heads SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); -------------------------------------------------------------------- -- Sequence-backed lane cursors (#295 pulled into v0.6). -- -- queue_enqueue_heads / queue_claim_heads remain as cold lane -- registries and lock targets. The hot cursor movement happens via -- PostgreSQL sequences, which are not MVCC heap tuples. This removes -- the per-claim/per-enqueue UPDATE dead-tuple stream while preserving -- the existing lane identity and SKIP LOCKED fairness shape. -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.queue_lane_sequence_name( p_prefix TEXT, p_queue TEXT, p_priority SMALLINT, p_enqueue_shard SMALLINT ) RETURNS TEXT LANGUAGE sql IMMUTABLE SET search_path = pg_catalog AS $func$ SELECT p_prefix || '_' || substr(md5(p_queue || ':' || p_priority::text || ':' || p_enqueue_shard::text), 1, 32) $func$ $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.sequence_next_value(p_seq_name TEXT) RETURNS BIGINT LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_last BIGINT; v_is_called BOOLEAN; BEGIN IF p_seq_name IS NULL THEN RAISE EXCEPTION 'lane sequence name is NULL' USING ERRCODE = '55000'; END IF; EXECUTE format('SELECT last_value, is_called FROM %%I.%%I', %1$L, p_seq_name) INTO v_last, v_is_called; IF v_is_called THEN RETURN v_last + 1; END IF; RETURN v_last; END; $func$ $ddl$, p_schema ); PERFORM awa.refresh_lane_sequence_helpers(p_schema); EXECUTE format( $ddl$ CREATE OR REPLACE FUNCTION %1$I.reserve_enqueue_seq( p_queue TEXT, p_priority SMALLINT, p_enqueue_shard SMALLINT, p_count BIGINT ) RETURNS BIGINT LANGUAGE plpgsql SET search_path = pg_catalog AS $func$ DECLARE v_seq_name TEXT; v_lock_key TEXT; v_start BIGINT; BEGIN IF p_count <= 0 THEN RETURN %1$I.sequence_next_value(( SELECT seq_name FROM %1$I.queue_enqueue_heads WHERE queue = p_queue AND priority = p_priority AND enqueue_shard = p_enqueue_shard )); END IF; PERFORM %1$I.ensure_lane_sequences(p_queue, p_priority, p_enqueue_shard); SELECT seq_name INTO v_seq_name FROM %1$I.queue_enqueue_heads WHERE queue = p_queue AND priority = p_priority AND enqueue_shard = p_enqueue_shard; IF v_seq_name IS NULL THEN RAISE EXCEPTION 'missing enqueue lane sequence for queue %%, priority %%, shard %%', p_queue, p_priority, p_enqueue_shard USING ERRCODE = '55000'; END IF; v_lock_key := format('%%I.%%I', %1$L, v_seq_name); -- Hold the lane reservation lock until the surrounding enqueue -- transaction ends. Sequence movement is non-transactional: if a -- later producer could reserve and commit lane N+1 while an -- earlier producer still holds uncommitted lane N, claim could -- advance past N and strand the earlier job when it eventually -- commits. The transaction-scoped lock preserves visibility order -- within a lane while aborted reservations still become harmless -- sequence gaps. PERFORM pg_advisory_xact_lock(hashtextextended(v_lock_key, 0)); EXECUTE format( 'SELECT nextval(%%L::regclass)::bigint', format('%%I.%%I', %1$L, v_seq_name) ) INTO v_start; IF p_count > 1 THEN EXECUTE format( 'SELECT setval(%%L::regclass, %%s, true)', format('%%I.%%I', %1$L, v_seq_name), v_start + p_count - 1 ); END IF; RETURN v_start; END; $func$ $ddl$, p_schema ); EXECUTE format( 'DROP TRIGGER IF EXISTS queue_enqueue_heads_sequence_sync ON %I.queue_enqueue_heads', p_schema ); EXECUTE format( 'CREATE TRIGGER queue_enqueue_heads_sequence_sync BEFORE INSERT OR UPDATE OF next_seq ON %I.queue_enqueue_heads FOR EACH ROW EXECUTE FUNCTION %I.queue_enqueue_head_sequence_sync()', p_schema, p_schema ); EXECUTE format( 'DROP TRIGGER IF EXISTS queue_claim_heads_sequence_sync ON %I.queue_claim_heads', p_schema ); EXECUTE format( 'CREATE TRIGGER queue_claim_heads_sequence_sync BEFORE INSERT OR UPDATE OF claim_seq ON %I.queue_claim_heads FOR EACH ROW EXECUTE FUNCTION %I.queue_claim_head_sequence_sync()', p_schema, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_terminal_rollups ( queue TEXT NOT NULL, priority SMALLINT NOT NULL, pruned_completed_count BIGINT NOT NULL DEFAULT 0, pruned_failed_count BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (queue, priority) ) $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_terminal_rollups ADD COLUMN IF NOT EXISTS pruned_failed_count BIGINT NOT NULL DEFAULT 0', p_schema ); -- #371: queue prune appends its per-(queue, priority) pruned terminal -- counts here instead of upserting `queue_terminal_rollups` in the -- prune transaction (an upsert under a pinned MVCC horizon leaves an -- unreclaimable dead rollup version per prune). The maintenance -- leader folds the deltas into the rollups when the horizon is clear; -- exact readers add the unfolded delta sums to their rollup reads. EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_terminal_rollup_deltas ( queue TEXT NOT NULL, priority SMALLINT NOT NULL, pruned_completed_delta BIGINT NOT NULL DEFAULT 0, pruned_failed_delta BIGINT NOT NULL DEFAULT 0, recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_claimer_leases ( queue TEXT NOT NULL, claimer_slot SMALLINT NOT NULL, owner_instance_id UUID NOT NULL, lease_epoch BIGINT NOT NULL DEFAULT 0, leased_at TIMESTAMPTZ NOT NULL, last_claimed_at TIMESTAMPTZ NOT NULL, expires_at TIMESTAMPTZ NOT NULL, PRIMARY KEY (queue, claimer_slot) ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_claimer_leases SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_claimer_state ( queue TEXT PRIMARY KEY, target_claimers SMALLINT NOT NULL, updated_at TIMESTAMPTZ NOT NULL ) $ddl$, p_schema ); -- Retain the current index: dropping it on every replay retains locks -- on each obsolete index OID until the whole migration range commits. v_claimer_owner_index := to_regclass(format( '%I.%I', p_schema, format('idx_%s_queue_claimer_leases_owner', p_schema) )); IF v_claimer_owner_index IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM pg_index AS idx JOIN pg_class AS rel ON rel.oid = idx.indexrelid JOIN pg_am AS am ON am.oid = rel.relam WHERE idx.indexrelid = v_claimer_owner_index AND idx.indrelid = to_regclass(format('%I.queue_claimer_leases', p_schema)) AND idx.indisvalid AND idx.indisready AND idx.indislive AND NOT idx.indisunique AND NOT idx.indisexclusion AND idx.indnkeyatts = 2 AND idx.indnatts = 2 AND idx.indpred IS NULL AND idx.indexprs IS NULL AND am.amname = 'btree' AND pg_get_indexdef(idx.indexrelid, 1, false) = 'queue' AND pg_get_indexdef(idx.indexrelid, 2, false) = 'owner_instance_id' ) THEN EXECUTE format('DROP INDEX %s', v_claimer_owner_index); END IF; EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_queue_claimer_leases_owner ON %I.queue_claimer_leases (queue, owner_instance_id)', p_schema, p_schema ); -- Seed enqueue/claim heads + terminal rollups from any pre-existing -- queue_lanes rows. Idempotent under ON CONFLICT. EXECUTE format( $ddl$ INSERT INTO %1$I.queue_enqueue_heads AS heads (queue, priority, enqueue_shard, next_seq) SELECT queue, priority, 0::smallint, next_seq FROM %1$I.queue_lanes ON CONFLICT (queue, priority, enqueue_shard) DO UPDATE SET next_seq = GREATEST(heads.next_seq, EXCLUDED.next_seq) $ddl$, p_schema ); EXECUTE format( $ddl$ INSERT INTO %1$I.queue_claim_heads AS heads (queue, priority, enqueue_shard, claim_seq) SELECT queue, priority, 0::smallint, claim_seq FROM %1$I.queue_lanes ON CONFLICT (queue, priority, enqueue_shard) DO UPDATE SET claim_seq = GREATEST(heads.claim_seq, EXCLUDED.claim_seq) $ddl$, p_schema ); EXECUTE format( $ddl$ SELECT %1$I.ensure_lane_sequences(lanes.queue, lanes.priority, lanes.enqueue_shard) FROM ( SELECT queue, priority, enqueue_shard FROM %1$I.queue_enqueue_heads UNION SELECT queue, priority, enqueue_shard FROM %1$I.queue_claim_heads ) AS lanes $ddl$, p_schema ); EXECUTE format( $ddl$ SELECT %1$I.set_sequence_next(seq_name, next_seq) FROM %1$I.queue_enqueue_heads WHERE seq_name IS NOT NULL $ddl$, p_schema ); EXECUTE format( $ddl$ SELECT %1$I.set_sequence_next(seq_name, claim_seq) FROM %1$I.queue_claim_heads WHERE seq_name IS NOT NULL $ddl$, p_schema ); EXECUTE format( $ddl$ INSERT INTO %1$I.queue_terminal_rollups AS rollups (queue, priority, pruned_completed_count) SELECT queue, priority, pruned_completed_count FROM %1$I.queue_lanes WHERE pruned_completed_count > 0 ON CONFLICT (queue, priority) DO UPDATE SET pruned_completed_count = GREATEST(rollups.pruned_completed_count, EXCLUDED.pruned_completed_count) $ddl$, p_schema ); EXECUTE format( 'UPDATE %I.queue_lanes SET pruned_completed_count = 0 WHERE pruned_completed_count > 0', p_schema ); -------------------------------------------------------------------- -- Partitioned leases / lease_claims / receipt closure evidence tables. -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.leases ( lease_slot INT NOT NULL, lease_generation BIGINT NOT NULL, ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, job_id BIGINT NOT NULL, queue TEXT NOT NULL, state awa.job_state NOT NULL DEFAULT 'running', priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL DEFAULT 1, run_lease BIGINT NOT NULL DEFAULT 1, max_attempts SMALLINT NOT NULL DEFAULT 25, lane_seq BIGINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, heartbeat_at TIMESTAMPTZ, deadline_at TIMESTAMPTZ, attempted_at TIMESTAMPTZ, callback_id UUID, callback_timeout_at TIMESTAMPTZ, PRIMARY KEY (lease_slot, queue, priority, enqueue_shard, lane_seq) ) PARTITION BY LIST (lease_slot) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.leases ADD COLUMN IF NOT EXISTS state awa.job_state NOT NULL DEFAULT 'running', ADD COLUMN IF NOT EXISTS enqueue_shard SMALLINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS heartbeat_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS deadline_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS attempted_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS callback_id UUID, ADD COLUMN IF NOT EXISTS callback_timeout_at TIMESTAMPTZ $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE SEQUENCE IF NOT EXISTS %I.lease_claim_receipt_id_seq $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE SEQUENCE IF NOT EXISTS %I.lease_claim_batch_id_seq $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE SEQUENCE IF NOT EXISTS %I.lease_claim_closure_batch_id_seq $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_claims ( claim_slot INT NOT NULL, receipt_id BIGINT NOT NULL DEFAULT nextval('%I.lease_claim_receipt_id_seq'::regclass), job_id BIGINT NOT NULL, run_lease BIGINT NOT NULL, ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL, max_attempts SMALLINT NOT NULL, lane_seq BIGINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, claimed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), materialized_at TIMESTAMPTZ, closed_at TIMESTAMPTZ, deadline_at TIMESTAMPTZ, PRIMARY KEY (claim_slot, job_id, run_lease) ) PARTITION BY LIST (claim_slot) $ddl$, p_schema, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_claim_batches ( claim_slot INT NOT NULL, batch_id BIGINT NOT NULL DEFAULT nextval('%I.lease_claim_batch_id_seq'::regclass), ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, claimed_count INT NOT NULL, job_ids BIGINT[] NOT NULL, run_leases BIGINT[] NOT NULL, receipt_ids BIGINT[] NOT NULL, receipt_ranges INT8MULTIRANGE NOT NULL, lane_seqs BIGINT[] NOT NULL, attempts SMALLINT[] NOT NULL, max_attempts SMALLINT[] NOT NULL, deadline_at TIMESTAMPTZ, claimed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (claim_slot, batch_id), CHECK (claimed_count > 0), CHECK (claimed_count = cardinality(job_ids)), CHECK (claimed_count = cardinality(run_leases)), CHECK (claimed_count = cardinality(receipt_ids)), CHECK (claimed_count = cardinality(lane_seqs)), CHECK (claimed_count = cardinality(attempts)), CHECK (claimed_count = cardinality(max_attempts)) ) PARTITION BY LIST (claim_slot) $ddl$, p_schema, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.lease_claim_batches IS %L', p_schema, 'Append-only compact receipt-claim ledger. Receipt claims store one row per claim batch here instead of one lease_claims row per job; cold paths expand by receipt_id and materialize only when needed.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_batches.receipt_ids IS %L', p_schema, 'Stable receipt identities assigned from lease_claim_receipt_id_seq for each claimed attempt in this batch. The worker handle carries these IDs through compact completion.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_batches.receipt_ranges IS %L', p_schema, 'Compact multirange derived from receipt_ids for exact indexed membership checks without unnested terminal history.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_batches.deadline_at IS %L', p_schema, 'Shared hard deadline for every claim in this batch (#246). All jobs claimed by one claim_ready_runtime call share one claimed_at, hence one deadline. NULL when the claiming queue has deadline_duration = 0. Batch deadline rescue scans this column via the per-partition partial deadline-cursor index.' ); EXECUTE format( $ddl$ DO $inner$ BEGIN IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = %1$L AND table_name = 'lease_claims' AND column_name = 'claim_seq' ) AND NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = %1$L AND table_name = 'lease_claims' AND column_name = 'receipt_id' ) THEN ALTER TABLE %1$I.lease_claims RENAME COLUMN claim_seq TO receipt_id; END IF; END $inner$ $ddl$, p_schema ); -- Idempotent column-add for upgrades from before receipts carried -- shard/deadline metadata. EXECUTE format( $ddl$ ALTER TABLE %I.lease_claims ADD COLUMN IF NOT EXISTS receipt_id BIGINT, ADD COLUMN IF NOT EXISTS enqueue_shard SMALLINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS closed_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS deadline_at TIMESTAMPTZ $ddl$, p_schema ); EXECUTE format( 'UPDATE %I.lease_claims SET receipt_id = nextval(%L::regclass) WHERE receipt_id IS NULL', p_schema, format('%I.lease_claim_receipt_id_seq', p_schema) ); EXECUTE format( 'ALTER TABLE %I.lease_claims ALTER COLUMN receipt_id SET DEFAULT nextval(%L::regclass)', p_schema, format('%I.lease_claim_receipt_id_seq', p_schema) ); EXECUTE format( 'ALTER TABLE %I.lease_claims ALTER COLUMN receipt_id SET NOT NULL', p_schema ); FOR v_slot IN 0..(p_claim_slot_count - 1) LOOP EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.lease_claims FOR VALUES IN (%s)', p_schema, format('lease_claims_%s', v_slot), p_schema, v_slot ); END LOOP; EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_stale ON %I.lease_claims (materialized_at, claimed_at, job_id)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_rescue_cursor ON %I.lease_claims (claimed_at, job_id, run_lease)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_deadline_brin ON %I.lease_claims USING BRIN (deadline_at) WITH (pages_per_range = 16)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_deadline_cursor ON %I.lease_claims (deadline_at, job_id, run_lease) WHERE deadline_at IS NOT NULL', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_job_run ON %I.lease_claims (job_id, run_lease)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claims_ready_ref ON %I.lease_claims (ready_slot, ready_generation)', p_schema, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_claim_closures ( claim_slot INT NOT NULL, job_id BIGINT NOT NULL, run_lease BIGINT NOT NULL, outcome TEXT NOT NULL, closed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (claim_slot, job_id, run_lease) ) PARTITION BY LIST (claim_slot) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.lease_claim_closure_batches ( claim_slot INT NOT NULL, ready_slot INT, ready_generation BIGINT, batch_id BIGINT NOT NULL DEFAULT nextval('%I.lease_claim_closure_batch_id_seq'::regclass), outcome TEXT NOT NULL, closed_count INT NOT NULL, receipt_ids BIGINT[] NOT NULL, receipt_ranges INT8MULTIRANGE NOT NULL, closed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (claim_slot, batch_id), CHECK (closed_count > 0), CHECK (closed_count = cardinality(receipt_ids)) ) PARTITION BY LIST (claim_slot) $ddl$, p_schema, p_schema ); EXECUTE format( $ddl$ DO $inner$ BEGIN IF EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = %1$L AND table_name = 'lease_claim_closure_batches' AND column_name = 'claim_seqs' ) AND NOT EXISTS ( SELECT 1 FROM information_schema.columns WHERE table_schema = %1$L AND table_name = 'lease_claim_closure_batches' AND column_name = 'receipt_ids' ) THEN ALTER TABLE %1$I.lease_claim_closure_batches RENAME COLUMN claim_seqs TO receipt_ids; END IF; END $inner$ $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.lease_claim_closure_batches ADD COLUMN IF NOT EXISTS receipt_ranges INT8MULTIRANGE', p_schema ); EXECUTE format( 'ALTER TABLE %I.lease_claim_closure_batches ADD COLUMN IF NOT EXISTS ready_slot INT', p_schema ); EXECUTE format( 'ALTER TABLE %I.lease_claim_closure_batches ADD COLUMN IF NOT EXISTS ready_generation BIGINT', p_schema ); EXECUTE format( $ddl$ UPDATE %1$I.lease_claim_closure_batches AS batch SET receipt_ranges = ranges.receipt_ranges FROM ( SELECT source.claim_slot, source.batch_id, range_agg(int8range(receipts.receipt_id, receipts.receipt_id + 1, '[)') ORDER BY receipts.receipt_id) AS receipt_ranges FROM %1$I.lease_claim_closure_batches AS source CROSS JOIN LATERAL unnest(source.receipt_ids) AS receipts(receipt_id) GROUP BY source.claim_slot, source.batch_id ) AS ranges WHERE batch.claim_slot = ranges.claim_slot AND batch.batch_id = ranges.batch_id AND batch.receipt_ranges IS DISTINCT FROM ranges.receipt_ranges $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.lease_claim_closure_batches ALTER COLUMN receipt_ranges SET NOT NULL', p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.lease_claim_closure_batches IS %L', p_schema, 'Append-only compact closure evidence for high-volume receipt completions. Each row closes a batch of immutable receipt claims by receipt_id, whether those claims live as row-local lease_claims rows or compact lease_claim_batches items, and is reclaimed with the matching claim-slot partition.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claims.receipt_id IS %L', p_schema, 'Stable exact identity for one immutable receipt claim. Compact closure batches store receipt_id values so open-claim proofs do not need to unnest terminal history arrays.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claims.closed_at IS %L', p_schema, 'Row-local closure fence set by explicit and rescue closure paths. Compact successful completions do not update this column; they close claims through lease_claim_closure_batches.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_closure_batches.receipt_ids IS %L', p_schema, 'Receipt identities closed by this compact batch. Kept as audit/debug data; hot closure proofs use receipt_ranges.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_closure_batches.receipt_ranges IS %L', p_schema, 'Compact multirange derived from receipt_ids for exact indexed closure membership checks. Membership is exact because receipt_id is assigned once per receipt claim from a global sequence.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_closure_batches.ready_slot IS %L', p_schema, 'Ready segment slot closed by this compact batch when all claims in the batch came from one ready segment. New compact completion batches populate this so prune can prove sealed segments by counts before falling back to per-claim closure membership checks.' ); EXECUTE format( 'COMMENT ON COLUMN %I.lease_claim_closure_batches.ready_generation IS %L', p_schema, 'Ready segment generation paired with ready_slot for exact count-based prune proofs.' ); FOR v_slot IN 0..(p_claim_slot_count - 1) LOOP EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.lease_claim_closures FOR VALUES IN (%s)', p_schema, format('lease_claim_closures_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.lease_claim_batches FOR VALUES IN (%s)', p_schema, format('lease_claim_batches_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_batches_%s_receipt_ranges ON %I.%I USING GIST (receipt_ranges)', p_schema, v_slot, p_schema, format('lease_claim_batches_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_batches_%s_ready_ref ON %I.%I (ready_slot, ready_generation)', p_schema, v_slot, p_schema, format('lease_claim_batches_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_batches_%s_rescue_cursor ON %I.%I (claimed_at, batch_id)', p_schema, v_slot, p_schema, format('lease_claim_batches_%s', v_slot) ); -- Batch deadline-rescue cursor scan (#246): compact deadline-backed -- claim batches are swept per slot ordered by (deadline_at, -- batch_id). Partial on deadline_at IS NOT NULL so the zero-deadline -- hot path (the common shape) never maintains index entries; one -- entry per claimed batch (not per job) keeps the index tiny even at -- saturation. EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_batches_%s_deadline_cursor ON %I.%I (deadline_at, batch_id) WHERE deadline_at IS NOT NULL', p_schema, v_slot, p_schema, format('lease_claim_batches_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.lease_claim_closure_batches FOR VALUES IN (%s)', p_schema, format('lease_claim_closure_batches_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_closure_batches_%s_receipt_ranges ON %I.%I USING GIST (receipt_ranges)', p_schema, v_slot, p_schema, format('lease_claim_closure_batches_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_closure_batches_%s_ready_ref ON %I.%I (ready_slot, ready_generation) WHERE ready_slot IS NOT NULL', p_schema, v_slot, p_schema, format('lease_claim_closure_batches_%s', v_slot) ); EXECUTE format( 'DROP INDEX IF EXISTS %I.%I', p_schema, format('idx_%s_lease_claim_closure_batches_%s_receipt_ids', p_schema, v_slot) ); END LOOP; PERFORM awa.refresh_claim_batch_job_index_helper(p_schema); -- The by-job lookups of compact claims use a GIN index that is only built -- on an empty partition whose lock is free (see -- awa.refresh_claim_batch_job_index_helper). A partition that is populated -- or busy now gains it after claim prune next empties it. FOR v_slot IN 0..(p_claim_slot_count - 1) LOOP BEGIN EXECUTE format('SELECT %I.ensure_claim_batch_job_index($1)', p_schema) USING v_slot; EXCEPTION WHEN insufficient_privilege THEN RAISE NOTICE 'claim slot % of schema % keeps scanning for job ids: %', v_slot, p_schema, SQLERRM; END; END LOOP; EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_lease_claim_closures_job_run ON %I.lease_claim_closures (job_id, run_lease)', p_schema, p_schema ); -------------------------------------------------------------------- -- Attempt state, ready_entries, ready_claim_attempt_batches, -- ready_tombstones, done_entries, deferred_jobs, dlq_entries. -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.attempt_state ( job_id BIGINT NOT NULL, run_lease BIGINT NOT NULL, heartbeat_at TIMESTAMPTZ, progress JSONB, callback_filter TEXT, callback_on_complete TEXT, callback_on_fail TEXT, callback_transform TEXT, callback_result JSONB, updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (job_id, run_lease) ) $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.attempt_state ADD COLUMN IF NOT EXISTS heartbeat_at TIMESTAMPTZ', p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.attempt_state SET ( fillfactor = 80, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.ready_entries ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, job_id BIGINT NOT NULL, kind TEXT NOT NULL, queue TEXT NOT NULL, args JSONB NOT NULL DEFAULT '{}'::jsonb, priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL DEFAULT 0, run_lease BIGINT NOT NULL DEFAULT 0, max_attempts SMALLINT NOT NULL DEFAULT 25, lane_seq BIGINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, run_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), attempted_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), unique_key BYTEA, unique_states TEXT, payload JSONB, PRIMARY KEY (ready_slot, queue, priority, enqueue_shard, lane_seq) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.ready_tombstones ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, lane_seq BIGINT NOT NULL, job_id BIGINT NOT NULL, tombstoned_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (ready_slot, queue, priority, enqueue_shard, lane_seq, ready_generation) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE SEQUENCE IF NOT EXISTS %I.ready_claim_attempt_batch_id_seq $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.ready_claim_attempt_batches ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, batch_id BIGINT NOT NULL DEFAULT nextval('%I.ready_claim_attempt_batch_id_seq'::regclass), queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, claim_slot INT, first_lane_seq BIGINT NOT NULL, next_lane_seq BIGINT NOT NULL, claimed_count INT NOT NULL, lane_ranges INT8MULTIRANGE NOT NULL, claimed_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (ready_slot, batch_id), CHECK (claimed_count > 0), CHECK (first_lane_seq < next_lane_seq) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.ready_claim_attempt_batches IS %L', p_schema, 'Append-only queue-slot-local ledger of emitted claim-attempt batches. Claim cursor recovery checks this compact lane-range evidence instead of scanning claim-ring partitions, and queue prune reclaims it with the matching ready segment.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_claim_attempt_batches.claim_slot IS %L', p_schema, 'Claim-ring slot that owns the full lease_claims receipt rows for this emitted attempt batch, when known. Upgrade backfills from terminal/deferred evidence may leave it NULL.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_claim_attempt_batches.lane_ranges IS %L', p_schema, 'Multirange of ready lane_seq values that emitted attempts in this batch; gaps represent lanes already proved spent by another ledger entry or tombstone.' ); EXECUTE format( 'COMMENT ON TABLE %I.ready_tombstones IS %L', p_schema, 'Append-only ledger of ready lanes that were made unavailable without deleting ready_entries; reclaimed with the matching ready-slot partition.' ); EXECUTE format( 'COMMENT ON COLUMN %I.ready_tombstones.ready_generation IS %L', p_schema, 'Generation guard for reused ready_slot partitions; prevents a tombstone from applying to a later ring generation.' ); EXECUTE format( $ddl$ CREATE SEQUENCE IF NOT EXISTS %I.receipt_completion_batch_id_seq $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.receipt_completion_batches ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, batch_id BIGINT NOT NULL DEFAULT nextval('%I.receipt_completion_batch_id_seq'::regclass), claim_slot INT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, completed_count INT NOT NULL, job_ids BIGINT[] NOT NULL, run_leases BIGINT[] NOT NULL, lane_seqs BIGINT[] NOT NULL, attempts SMALLINT[] NOT NULL, attempted_ats TIMESTAMPTZ[] NOT NULL, finalized_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), outputs JSON[], PRIMARY KEY (ready_slot, batch_id), CHECK (completed_count > 0), CHECK (completed_count = cardinality(job_ids)), CHECK (completed_count = cardinality(run_leases)), CHECK (completed_count = cardinality(lane_seqs)), CHECK (completed_count = cardinality(attempts)), CHECK (completed_count = cardinality(attempted_ats)), CONSTRAINT receipt_completion_batches_outputs_cardinality CHECK (outputs IS NULL OR completed_count = cardinality(outputs)) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.receipt_completion_batches IS %L', p_schema, 'Append-only compact history for successful receipt-backed completions. Each row stores one completion batch and expands through terminal_jobs; matching receipt claims are closed through lease_claim_closure_batches in the claim ring.' ); EXECUTE format( 'COMMENT ON COLUMN %I.receipt_completion_batches.job_ids IS %L', p_schema, 'Completed job ids for this receipt batch, positionally aligned with run_leases, lane_seqs, attempts, and attempted_ats.' ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.receipt_completion_tombstones ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, job_id BIGINT NOT NULL, run_lease BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, lane_seq BIGINT NOT NULL, deleted_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (ready_slot, job_id, run_lease) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.receipt_completion_tombstones IS %L', p_schema, 'Cold-path deletion ledger for completed rows synthesized from receipt_completion_batches; hot completion never writes here.' ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.done_entries ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, job_id BIGINT NOT NULL, kind TEXT NOT NULL, queue TEXT NOT NULL, args JSONB, state awa.job_state NOT NULL DEFAULT 'completed', priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL DEFAULT 1, run_lease BIGINT NOT NULL DEFAULT 1, max_attempts SMALLINT, lane_seq BIGINT NOT NULL, enqueue_shard SMALLINT NOT NULL DEFAULT 0, run_at TIMESTAMPTZ, attempted_at TIMESTAMPTZ, finalized_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), created_at TIMESTAMPTZ, unique_key BYTEA, unique_states TEXT, payload JSONB, output JSON, PRIMARY KEY (ready_slot, queue, priority, enqueue_shard, lane_seq) ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_terminal_count_deltas ( ready_slot INT NOT NULL, ready_generation BIGINT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL, counter_bucket SMALLINT NOT NULL DEFAULT 0, terminal_delta BIGINT NOT NULL, recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() ) PARTITION BY LIST (ready_slot) $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_terminal_count_deltas ADD COLUMN IF NOT EXISTS recorded_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()', p_schema ); EXECUTE format( $ddl$ DO $inner$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_constraint AS c JOIN pg_class AS t ON t.oid = c.conrelid JOIN pg_namespace AS n ON n.oid = t.relnamespace WHERE n.nspname = %1$L AND t.relname = 'queue_terminal_count_deltas' AND c.conname = 'queue_terminal_count_deltas_nonzero' ) THEN ALTER TABLE %1$I.queue_terminal_count_deltas ADD CONSTRAINT queue_terminal_count_deltas_nonzero CHECK (terminal_delta <> 0); END IF; END $inner$ $ddl$, p_schema ); EXECUTE format( 'COMMENT ON TABLE %I.queue_terminal_count_deltas IS %L', p_schema, 'Append-only signed terminal-count deltas. Completion/delete paths insert here; maintenance folds sealed-slot deltas into queue_terminal_live_counts when no visible backend snapshot or idle transaction id pins the MVCC horizon, and queue prune truncates the matching partition.' ); EXECUTE format( 'COMMENT ON COLUMN %I.queue_terminal_count_deltas.ready_generation IS %L', p_schema, 'Generation guard for reused ready_slot partitions; rollup folds only deltas belonging to the sealed generation it is processing.' ); EXECUTE format( 'COMMENT ON COLUMN %I.queue_terminal_count_deltas.terminal_delta IS %L', p_schema, 'Signed change to terminal row cardinality for the grouped lane bucket; positive for terminal inserts and negative for terminal deletes.' ); EXECUTE format( $ddl$ ALTER TABLE %I.done_entries ADD COLUMN IF NOT EXISTS args JSONB, ADD COLUMN IF NOT EXISTS state awa.job_state NOT NULL DEFAULT 'completed', ADD COLUMN IF NOT EXISTS max_attempts SMALLINT, ADD COLUMN IF NOT EXISTS enqueue_shard SMALLINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS run_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS attempted_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS unique_key BYTEA, ADD COLUMN IF NOT EXISTS unique_states TEXT, ADD COLUMN IF NOT EXISTS payload JSONB $ddl$, p_schema ); -- Narrow terminal history: see queue_storage.rs comment. EXECUTE format( $ddl$ ALTER TABLE %I.done_entries ALTER COLUMN args DROP NOT NULL, ALTER COLUMN args DROP DEFAULT, ALTER COLUMN max_attempts DROP NOT NULL, ALTER COLUMN max_attempts DROP DEFAULT, ALTER COLUMN run_at DROP NOT NULL, ALTER COLUMN run_at DROP DEFAULT, ALTER COLUMN created_at DROP NOT NULL, ALTER COLUMN created_at DROP DEFAULT $ddl$, p_schema ); -- Retained job output (ADR-048): the output columns and the -- terminal_jobs view that exposes them. PERFORM awa.install_queue_storage_job_output(p_schema); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.deferred_jobs ( job_id BIGINT PRIMARY KEY, kind TEXT NOT NULL, queue TEXT NOT NULL, args JSONB NOT NULL DEFAULT '{}'::jsonb, state awa.job_state NOT NULL, priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL DEFAULT 0, run_lease BIGINT NOT NULL DEFAULT 0, max_attempts SMALLINT NOT NULL DEFAULT 25, run_at TIMESTAMPTZ NOT NULL, attempted_at TIMESTAMPTZ, finalized_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), unique_key BYTEA, unique_states TEXT, payload JSONB, CONSTRAINT deferred_jobs_state_check CHECK (state IN ('scheduled', 'retryable')) ) $ddl$, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.deferred_jobs ADD COLUMN IF NOT EXISTS args JSONB NOT NULL DEFAULT '{}'::jsonb, ADD COLUMN IF NOT EXISTS state awa.job_state NOT NULL DEFAULT 'scheduled', ADD COLUMN IF NOT EXISTS attempt SMALLINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS run_lease BIGINT NOT NULL DEFAULT 0, ADD COLUMN IF NOT EXISTS max_attempts SMALLINT NOT NULL DEFAULT 25, ADD COLUMN IF NOT EXISTS attempted_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS finalized_at TIMESTAMPTZ, ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), ADD COLUMN IF NOT EXISTS unique_key BYTEA, ADD COLUMN IF NOT EXISTS unique_states TEXT, ADD COLUMN IF NOT EXISTS payload JSONB $ddl$, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_deferred_due ON %I.deferred_jobs (state, run_at, queue, priority, job_id)', p_schema, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_deferred_job_unique ON %I.deferred_jobs (unique_key)', p_schema, p_schema ); EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.dlq_entries ( job_id BIGINT PRIMARY KEY, kind TEXT NOT NULL, queue TEXT NOT NULL, args JSONB NOT NULL DEFAULT '{}'::jsonb, state awa.job_state NOT NULL DEFAULT 'failed', priority SMALLINT NOT NULL, attempt SMALLINT NOT NULL DEFAULT 1, run_lease BIGINT NOT NULL DEFAULT 1, max_attempts SMALLINT NOT NULL DEFAULT 25, run_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), attempted_at TIMESTAMPTZ, finalized_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), unique_key BYTEA, unique_states TEXT, payload JSONB, dlq_reason TEXT NOT NULL, dlq_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), original_run_lease BIGINT NOT NULL ) $ddl$, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_dlq_queue_time ON %I.dlq_entries (queue, dlq_at DESC)', p_schema, p_schema ); -------------------------------------------------------------------- -- ready_entries / ready_claim_attempt_batches / ready_tombstones / -- ready_segments / -- receipt_completion_batches / receipt_completion_tombstones / -- done_entries / queue_terminal_count_deltas partitions + lane indexes. -------------------------------------------------------------------- FOR v_slot IN 0..(p_queue_slot_count - 1) LOOP EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.ready_entries FOR VALUES IN (%s)', p_schema, format('ready_entries_%s', v_slot), p_schema, v_slot ); -- Lane lookups on ready children always pin ready_slot, so the -- partition primary key (ready_slot, queue, priority, enqueue_shard, -- lane_seq) is the lane index; v050 dropped the separate lane_shard -- copy. EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_%s_job ON %I.%I (job_id)', p_schema, v_slot, p_schema, format('ready_entries_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.ready_tombstones FOR VALUES IN (%s)', p_schema, format('ready_tombstones_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.ready_claim_attempt_batches FOR VALUES IN (%s)', p_schema, format('ready_claim_attempt_batches_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.ready_segments FOR VALUES IN (%s)', p_schema, format('ready_segments_%s', v_slot), p_schema, v_slot ); EXECUTE format( $ddl$ ALTER TABLE %I.%I SET ( fillfactor = 90, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema, format('ready_segments_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_claim_attempt_batches_%s_lane ON %I.%I (ready_generation, queue, priority, enqueue_shard, next_lane_seq, first_lane_seq)', p_schema, v_slot, p_schema, format('ready_claim_attempt_batches_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_claim_attempt_batches_%s_claim_slot ON %I.%I (claim_slot) WHERE claim_slot IS NOT NULL', p_schema, v_slot, p_schema, format('ready_claim_attempt_batches_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_tombstones_%s_lane_shard ON %I.%I (queue, priority, enqueue_shard, lane_seq)', p_schema, v_slot, p_schema, format('ready_tombstones_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_ready_tombstones_%s_job ON %I.%I (job_id)', p_schema, v_slot, p_schema, format('ready_tombstones_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.receipt_completion_batches FOR VALUES IN (%s)', p_schema, format('receipt_completion_batches_%s', v_slot), p_schema, v_slot ); -- Compatibility deletion can find a job by expanding retained compact -- batches. Keep that cold path off the completion hot path: a GIN -- index on job_ids was larger than the retained batch table during -- soak tests and had to be maintained for every successful completion. EXECUTE format( 'DROP INDEX IF EXISTS %I.%I', p_schema, format('idx_%s_receipt_completion_batches_%s_job_ids', p_schema, v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_receipt_completion_batches_%s_lane ON %I.%I (ready_generation, queue, priority, enqueue_shard)', p_schema, v_slot, p_schema, format('receipt_completion_batches_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.receipt_completion_tombstones FOR VALUES IN (%s)', p_schema, format('receipt_completion_tombstones_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_receipt_completion_tombstones_%s_job ON %I.%I (job_id, run_lease)', p_schema, v_slot, p_schema, format('receipt_completion_tombstones_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.done_entries FOR VALUES IN (%s)', p_schema, format('done_entries_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_done_%s_lane_shard ON %I.%I (queue, priority, enqueue_shard, lane_seq)', p_schema, v_slot, p_schema, format('done_entries_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_done_%s_job ON %I.%I (job_id)', p_schema, v_slot, p_schema, format('done_entries_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_done_%s_failed_queue ON %I.%I (queue) WHERE state = ''failed''::awa.job_state', p_schema, v_slot, p_schema, format('done_entries_%s', v_slot) ); EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.queue_terminal_count_deltas FOR VALUES IN (%s)', p_schema, format('queue_terminal_count_deltas_%s', v_slot), p_schema, v_slot ); END LOOP; IF to_regclass(format('%I.%I', p_schema, 'ready_segments_unpartitioned')) IS NOT NULL THEN EXECUTE format( $ddl$ INSERT INTO %1$I.ready_segments ( ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq, next_lane_seq, first_run_at, created_at ) SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq, next_lane_seq, first_run_at, created_at FROM %1$I.ready_segments_unpartitioned ON CONFLICT (ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq) DO NOTHING $ddl$, p_schema ); EXECUTE format('DROP TABLE %I.ready_segments_unpartitioned', p_schema); END IF; -- Backfill queue-slot-local claim evidence for schemas upgraded while -- receipts were already in flight. New claims write this ledger in the -- same transaction as lease_claims. Existing schemas can already have -- live claim rows, compact receipt batches, terminal rows, lease rows, -- deferred rows, DLQ rows, or re-appended ready rows proving that a -- retained ready lane emitted run_lease+1 before this ledger existed. EXECUTE format( $ddl$ WITH attempts AS ( SELECT claims.ready_slot, claims.ready_generation, claims.queue, COALESCE(ready.priority, claims.priority) AS priority, claims.enqueue_shard, claims.claim_slot, claims.lane_seq, claims.claimed_at FROM %1$I.lease_claims AS claims LEFT JOIN %1$I.ready_entries AS ready ON ready.ready_slot = claims.ready_slot AND ready.ready_generation = claims.ready_generation AND ready.queue = claims.queue AND ready.enqueue_shard = claims.enqueue_shard AND ready.lane_seq = claims.lane_seq AND ready.job_id = claims.job_id ), missing_attempts AS ( SELECT attempts.* FROM attempts WHERE NOT EXISTS ( SELECT 1 FROM %1$I.ready_claim_attempt_batches AS existing WHERE existing.ready_slot = attempts.ready_slot AND existing.ready_generation = attempts.ready_generation AND existing.queue = attempts.queue AND existing.priority = attempts.priority AND existing.enqueue_shard = attempts.enqueue_shard AND existing.first_lane_seq <= attempts.lane_seq AND existing.next_lane_seq > attempts.lane_seq AND existing.lane_ranges @> int8range(attempts.lane_seq, attempts.lane_seq + 1, '[)') ) ), grouped AS ( SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, min(lane_seq)::bigint AS first_lane_seq, (max(lane_seq) + 1)::bigint AS next_lane_seq, count(*)::int AS claimed_count, range_agg(int8range(lane_seq, lane_seq + 1, '[)') ORDER BY lane_seq)::int8multirange AS lane_ranges, max(claimed_at) AS claimed_at FROM missing_attempts GROUP BY ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot ) INSERT INTO %1$I.ready_claim_attempt_batches ( ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at ) SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at FROM grouped $ddl$, p_schema ); EXECUTE format( $ddl$ WITH attempts AS ( SELECT batch.ready_slot, batch.ready_generation, batch.queue, COALESCE(ready.priority, batch.priority) AS priority, batch.enqueue_shard, batch.claim_slot, completed.lane_seq, batch.finalized_at AS claimed_at FROM %1$I.receipt_completion_batches AS batch CROSS JOIN LATERAL unnest(batch.job_ids, batch.lane_seqs) AS completed(job_id, lane_seq) LEFT JOIN %1$I.ready_entries AS ready ON ready.ready_slot = batch.ready_slot AND ready.ready_generation = batch.ready_generation AND ready.queue = batch.queue AND ready.enqueue_shard = batch.enqueue_shard AND ready.lane_seq = completed.lane_seq AND ready.job_id = completed.job_id ), missing_attempts AS ( SELECT attempts.* FROM attempts WHERE NOT EXISTS ( SELECT 1 FROM %1$I.ready_claim_attempt_batches AS existing WHERE existing.ready_slot = attempts.ready_slot AND existing.ready_generation = attempts.ready_generation AND existing.queue = attempts.queue AND existing.priority = attempts.priority AND existing.enqueue_shard = attempts.enqueue_shard AND existing.first_lane_seq <= attempts.lane_seq AND existing.next_lane_seq > attempts.lane_seq AND existing.lane_ranges @> int8range(attempts.lane_seq, attempts.lane_seq + 1, '[)') ) ), grouped AS ( SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, min(lane_seq)::bigint AS first_lane_seq, (max(lane_seq) + 1)::bigint AS next_lane_seq, count(*)::int AS claimed_count, range_agg(int8range(lane_seq, lane_seq + 1, '[)') ORDER BY lane_seq)::int8multirange AS lane_ranges, max(claimed_at) AS claimed_at FROM missing_attempts GROUP BY ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot ) INSERT INTO %1$I.ready_claim_attempt_batches ( ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at ) SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at FROM grouped $ddl$, p_schema ); EXECUTE format( $ddl$ WITH attempts AS ( SELECT ready.ready_slot, ready.ready_generation, ready.queue, ready.priority, ready.enqueue_shard, NULL::int AS claim_slot, ready.lane_seq, clock_timestamp() AS claimed_at FROM %1$I.ready_entries AS ready WHERE EXISTS ( SELECT 1 FROM %1$I.leases AS leases WHERE leases.job_id = ready.job_id AND leases.run_lease = ready.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.done_entries AS done WHERE done.job_id = ready.job_id AND done.run_lease = ready.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.deferred_jobs AS deferred WHERE deferred.job_id = ready.job_id AND deferred.run_lease = ready.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.dlq_entries AS dlq WHERE dlq.job_id = ready.job_id AND dlq.run_lease = ready.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.ready_entries AS newer_ready WHERE newer_ready.job_id = ready.job_id AND newer_ready.run_lease = ready.run_lease + 1 ) ), missing_attempts AS ( SELECT attempts.* FROM attempts WHERE NOT EXISTS ( SELECT 1 FROM %1$I.ready_claim_attempt_batches AS existing WHERE existing.ready_slot = attempts.ready_slot AND existing.ready_generation = attempts.ready_generation AND existing.queue = attempts.queue AND existing.priority = attempts.priority AND existing.enqueue_shard = attempts.enqueue_shard AND existing.first_lane_seq <= attempts.lane_seq AND existing.next_lane_seq > attempts.lane_seq AND existing.lane_ranges @> int8range(attempts.lane_seq, attempts.lane_seq + 1, '[)') ) ), grouped AS ( SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, min(lane_seq)::bigint AS first_lane_seq, (max(lane_seq) + 1)::bigint AS next_lane_seq, count(*)::int AS claimed_count, range_agg(int8range(lane_seq, lane_seq + 1, '[)') ORDER BY lane_seq)::int8multirange AS lane_ranges, max(claimed_at) AS claimed_at FROM missing_attempts GROUP BY ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot ) INSERT INTO %1$I.ready_claim_attempt_batches ( ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at ) SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at FROM grouped $ddl$, p_schema ); -- Backfill ready segment metadata for existing committed ready rows. -- Runtime enqueue writes one segment per contiguous lane range with the -- same run_at. Claim computes priority aging from this compact metadata, -- so splitting on run_at keeps the lane-head aging timestamp exact even -- after the claim cursor advances inside a multi-row segment. Upgraded -- schemas can already contain ready rows before the table existed. -- Segment rows are compact control-plane metadata; the owning ready-slot -- child is truncated with the rest of the queue-ring family. EXECUTE format( $ddl$ WITH ordered AS ( SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, lane_seq, run_at, lane_seq - row_number() OVER ( PARTITION BY ready_slot, ready_generation, queue, priority, enqueue_shard, run_at ORDER BY lane_seq )::bigint AS contiguous_group FROM %1$I.ready_entries ), segments AS ( SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, min(lane_seq)::bigint AS first_lane_seq, (max(lane_seq) + 1)::bigint AS next_lane_seq, run_at AS first_run_at FROM ordered GROUP BY ready_slot, ready_generation, queue, priority, enqueue_shard, run_at, contiguous_group ) INSERT INTO %1$I.ready_segments ( ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq, next_lane_seq, first_run_at ) SELECT ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq, next_lane_seq, first_run_at FROM segments ON CONFLICT (ready_slot, ready_generation, queue, priority, enqueue_shard, first_lane_seq) DO NOTHING $ddl$, p_schema ); -------------------------------------------------------------------- -- queue_terminal_live_counts (#290). -------------------------------------------------------------------- EXECUTE format( $ddl$ CREATE TABLE IF NOT EXISTS %I.queue_terminal_live_counts ( ready_slot INT NOT NULL, queue TEXT NOT NULL, priority SMALLINT NOT NULL, enqueue_shard SMALLINT NOT NULL, counter_bucket SMALLINT NOT NULL DEFAULT 0, live_terminal_count BIGINT NOT NULL DEFAULT 0, PRIMARY KEY (ready_slot, queue, priority, enqueue_shard, counter_bucket) ) $ddl$, p_schema ); EXECUTE format( 'ALTER TABLE %I.queue_terminal_live_counts ADD COLUMN IF NOT EXISTS counter_bucket SMALLINT NOT NULL DEFAULT 0', p_schema ); -- If an upgraded schema already had live-counter rows before -- counter_bucket existed, every aggregate row received DEFAULT 0. -- The aggregate table has no job_id, so the installer cannot rebucket -- those rows in place. Mark the counter untrusted only when the old -- primary-key shape is still present; idempotent prepare_schema() calls on -- an already-current schema must not clear a trusted marker. EXECUTE format( $ddl$ UPDATE %1$I.queue_ring_state SET terminal_counter_trusted_at = NULL WHERE singleton = TRUE AND EXISTS (SELECT 1 FROM %1$I.queue_terminal_live_counts LIMIT 1) AND EXISTS (SELECT 1 FROM %1$I.done_entries LIMIT 1) AND NOT EXISTS ( SELECT 1 FROM pg_constraint AS c JOIN pg_class AS t ON t.oid = c.conrelid JOIN pg_namespace AS n ON n.oid = t.relnamespace WHERE n.nspname = %1$L AND t.relname = 'queue_terminal_live_counts' AND c.contype = 'p' AND EXISTS ( SELECT 1 FROM unnest(c.conkey) AS key(attnum) JOIN pg_attribute AS a ON a.attrelid = t.oid AND a.attnum = key.attnum WHERE a.attname = 'counter_bucket' ) ) $ddl$, p_schema ); EXECUTE format( $ddl$ DO $inner$ DECLARE v_has_bucket_key BOOLEAN; BEGIN SELECT EXISTS ( SELECT 1 FROM pg_constraint AS c JOIN pg_class AS t ON t.oid = c.conrelid JOIN pg_namespace AS n ON n.oid = t.relnamespace WHERE n.nspname = %1$L AND t.relname = 'queue_terminal_live_counts' AND c.contype = 'p' AND EXISTS ( SELECT 1 FROM unnest(c.conkey) AS key(attnum) JOIN pg_attribute AS a ON a.attrelid = t.oid AND a.attnum = key.attnum WHERE a.attname = 'counter_bucket' ) ) INTO v_has_bucket_key; IF NOT v_has_bucket_key THEN ALTER TABLE %1$I.queue_terminal_live_counts DROP CONSTRAINT IF EXISTS queue_terminal_live_counts_pkey; ALTER TABLE %1$I.queue_terminal_live_counts ADD CONSTRAINT queue_terminal_live_counts_pkey PRIMARY KEY (ready_slot, queue, priority, enqueue_shard, counter_bucket); END IF; END $inner$ $ddl$, p_schema ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_queue_terminal_live_counts_queue ON %I.queue_terminal_live_counts (queue, priority)', p_schema, p_schema ); EXECUTE format( $ddl$ ALTER TABLE %I.queue_terminal_live_counts SET ( fillfactor = 50, autovacuum_vacuum_scale_factor = 0.0, autovacuum_vacuum_threshold = 200, autovacuum_vacuum_cost_limit = 2000, autovacuum_vacuum_cost_delay = 2 ) $ddl$, p_schema ); -- Backfill from existing done_entries (no-op on fresh installs). EXECUTE format( $ddl$ INSERT INTO %1$I.queue_terminal_live_counts AS counts ( ready_slot, queue, priority, enqueue_shard, counter_bucket, live_terminal_count ) SELECT ready_slot, queue, priority, enqueue_shard, mod(mod(job_id, 256::bigint) + 256::bigint, 256::bigint)::smallint AS counter_bucket, count(*)::bigint FROM %1$I.done_entries WHERE NOT EXISTS ( SELECT 1 FROM %1$I.queue_terminal_live_counts LIMIT 1 ) GROUP BY ready_slot, queue, priority, enqueue_shard, counter_bucket ON CONFLICT (ready_slot, queue, priority, enqueue_shard, counter_bucket) DO NOTHING $ddl$, p_schema ); -- Auto-mark trusted for fresh installs where done_entries is empty. EXECUTE format( $ddl$ UPDATE %1$I.queue_ring_state SET terminal_counter_trusted_at = now() WHERE singleton = TRUE AND terminal_counter_trusted_at IS NULL AND NOT EXISTS (SELECT 1 FROM %1$I.done_entries LIMIT 1) $ddl$, p_schema ); -------------------------------------------------------------------- -- leases partitions + indexes. -------------------------------------------------------------------- FOR v_slot IN 0..(p_lease_slot_count - 1) LOOP EXECUTE format( 'CREATE TABLE IF NOT EXISTS %I.%I PARTITION OF %I.leases FOR VALUES IN (%s)', p_schema, format('leases_%s', v_slot), p_schema, v_slot ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_lane_shard ON %I.%I (queue, priority, enqueue_shard, lane_seq)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_ready_ref ON %I.%I (ready_slot, ready_generation)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_job ON %I.%I (job_id, run_lease)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_callback ON %I.%I (callback_id)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); -- #169 B1: idx_state_hb dropped. In receipts mode (the only -- supported shape for the default `awa` schema) -- `leases.heartbeat_at` is never written, so the index would -- be empty; the rescue path reads `attempt_state.heartbeat_at` -- instead. Legacy non-receipts custom schemas fall back to a -- seq-scan of `WHERE state='running'` rows (bounded by live -- worker count, called at 30s cadence) — acceptable. v025 -- drops the index from existing 0.6 deployments. EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_state_deadline ON %I.%I (state, deadline_at)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); EXECUTE format( 'CREATE INDEX IF NOT EXISTS idx_%s_leases_%s_state_callback_timeout ON %I.%I (state, callback_timeout_at)', p_schema, v_slot, p_schema, format('leases_%s', v_slot) ); END LOOP; -------------------------------------------------------------------- -- claim_ready_runtime() function. The claim CTE branches on the -- receipts mode: receipts=TRUE writes compact claim batches into -- lease_claim_batches (ADR-023); receipts=FALSE writes directly into -- the partitioned leases table. -- -- Every job claimed by one call shares v_claimed_at, so a claim batch -- has exactly one deadline value: deadline-backed claims (#246) use -- the same compact representation with the batch's deadline_at -- populated instead of one lease_claims row per job. Row-local -- lease_claims rows are no longer written by the claim path; the -- table remains for legacy in-flight claims mid-upgrade and keeps its -- deadline-rescue machinery. -------------------------------------------------------------------- IF p_lease_claim_receipts THEN v_claimed_cte := format( $cte$ claim_ring AS MATERIALIZED ( -- #371: current claim cursor via the authority resolver -- (columns in compat mode, max-generation ledger row in -- ledger mode). MATERIALIZED pins it to a single evaluation: -- this single-reference CTE would otherwise be inlined and -- re-run the resolver once per selected row (loops=N) on the -- inner side of the claim_attempt_batches nested loop. The -- pre-ledger claim_ring_state singleton was one cached read, -- so the per-row re-execution regressed claim yield; one -- authority-row read + one O(1) cursor read, materialized, -- keeps loops=1. SELECT slot AS claim_slot FROM %1$I.ring_cursor('claim') ), claim_attempt_batches AS ( INSERT INTO %1$I.ready_claim_attempt_batches AS attempt_rows ( ready_slot, ready_generation, queue, priority, enqueue_shard, claim_slot, first_lane_seq, next_lane_seq, claimed_count, lane_ranges, claimed_at ) SELECT selected.ready_slot, selected.ready_generation, selected.queue, selected.lane_priority, v_lane_shard, claim_ring.claim_slot, min(selected.lane_seq)::bigint AS first_lane_seq, (max(selected.lane_seq) + 1)::bigint AS next_lane_seq, count(*)::int AS claimed_count, range_agg(int8range(selected.lane_seq, selected.lane_seq + 1, '[)') ORDER BY selected.lane_seq)::int8multirange AS lane_ranges, v_claimed_at FROM selected_with_spent AS selected CROSS JOIN claim_ring WHERE NOT selected.attempt_spent GROUP BY selected.ready_slot, selected.ready_generation, selected.queue, selected.lane_priority, claim_ring.claim_slot RETURNING attempt_rows.claim_slot, attempt_rows.ready_slot, attempt_rows.ready_generation, attempt_rows.queue, attempt_rows.priority AS lane_priority, attempt_rows.enqueue_shard, attempt_rows.first_lane_seq, attempt_rows.next_lane_seq, attempt_rows.lane_ranges ), claim_items AS MATERIALIZED ( SELECT attempts.claim_slot, selected.ready_slot, selected.ready_generation, selected.job_id, selected.queue, selected.effective_priority AS priority, selected.lane_seq, v_lane_shard AS enqueue_shard, (selected.attempt + 1)::smallint AS attempt, (selected.run_lease + 1)::bigint AS run_lease, selected.max_attempts::smallint AS max_attempts, nextval('%1$I.lease_claim_receipt_id_seq'::regclass)::bigint AS receipt_id, row_number() OVER ( PARTITION BY attempts.claim_slot, selected.ready_slot, selected.ready_generation, selected.queue, selected.effective_priority, v_lane_shard ORDER BY selected.lane_seq, selected.job_id )::int AS claim_batch_index FROM selected_with_spent AS selected JOIN claim_attempt_batches AS attempts ON attempts.ready_slot = selected.ready_slot AND attempts.ready_generation = selected.ready_generation AND attempts.queue = selected.queue AND attempts.lane_priority = selected.lane_priority AND attempts.enqueue_shard = v_lane_shard AND attempts.first_lane_seq <= selected.lane_seq AND attempts.next_lane_seq > selected.lane_seq AND attempts.lane_ranges @> int8range(selected.lane_seq, selected.lane_seq + 1, '[)') WHERE NOT selected.attempt_spent ), compact_claim_batches AS ( INSERT INTO %1$I.lease_claim_batches AS claim_batches ( claim_slot, ready_slot, ready_generation, queue, priority, enqueue_shard, claimed_count, job_ids, run_leases, receipt_ids, receipt_ranges, lane_seqs, attempts, max_attempts, deadline_at, claimed_at ) SELECT claim_items.claim_slot, claim_items.ready_slot, claim_items.ready_generation, claim_items.queue, claim_items.priority, claim_items.enqueue_shard, count(*)::int AS claimed_count, array_agg(claim_items.job_id ORDER BY claim_items.lane_seq, claim_items.job_id), array_agg(claim_items.run_lease ORDER BY claim_items.lane_seq, claim_items.job_id), array_agg(claim_items.receipt_id ORDER BY claim_items.lane_seq, claim_items.job_id), range_agg(int8range(claim_items.receipt_id, claim_items.receipt_id + 1, '[)') ORDER BY claim_items.receipt_id), array_agg(claim_items.lane_seq ORDER BY claim_items.lane_seq, claim_items.job_id), array_agg(claim_items.attempt ORDER BY claim_items.lane_seq, claim_items.job_id), array_agg(claim_items.max_attempts ORDER BY claim_items.lane_seq, claim_items.job_id), v_deadline_at, v_claimed_at FROM claim_items GROUP BY claim_items.claim_slot, claim_items.ready_slot, claim_items.ready_generation, claim_items.queue, claim_items.priority, claim_items.enqueue_shard RETURNING claim_batches.claim_slot, claim_batches.batch_id, claim_batches.ready_slot, claim_batches.ready_generation, claim_batches.queue, claim_batches.priority, claim_batches.enqueue_shard ), claimed AS ( SELECT claim_items.claim_slot, claim_items.receipt_id, batches.batch_id AS claim_batch_id, claim_items.claim_batch_index, claim_items.ready_slot, claim_items.ready_generation, claim_items.job_id, claim_items.queue, claim_items.priority, claim_items.lane_seq, claim_items.attempt, claim_items.run_lease, claim_items.max_attempts FROM claim_items JOIN compact_claim_batches AS batches ON batches.claim_slot = claim_items.claim_slot AND batches.ready_slot = claim_items.ready_slot AND batches.ready_generation = claim_items.ready_generation AND batches.queue = claim_items.queue AND batches.priority = claim_items.priority AND batches.enqueue_shard = claim_items.enqueue_shard ) $cte$, p_schema ); ELSE v_claimed_cte := format( $cte$ claimed AS ( INSERT INTO %1$I.leases AS lease_rows ( lease_slot, lease_generation, ready_slot, ready_generation, job_id, queue, state, priority, attempt, run_lease, max_attempts, lane_seq, enqueue_shard, heartbeat_at, deadline_at, attempted_at ) SELECT lease_ring.lease_slot, lease_ring.lease_generation, selected.ready_slot, selected.ready_generation, selected.job_id, selected.queue, 'running'::awa.job_state, selected.effective_priority, selected.attempt + 1, selected.run_lease + 1, selected.max_attempts, selected.lane_seq, v_lane_shard, v_claimed_at, v_deadline_at, v_claimed_at FROM selected_with_spent AS selected CROSS JOIN lease_ring WHERE NOT selected.attempt_spent RETURNING 0::int AS claim_slot, NULL::bigint AS receipt_id, NULL::bigint AS claim_batch_id, NULL::int AS claim_batch_index, lease_rows.ready_slot, lease_rows.ready_generation, lease_rows.lease_slot, lease_rows.lease_generation, lease_rows.queue, lease_rows.priority, lease_rows.lane_seq, lease_rows.attempt, lease_rows.run_lease, lease_rows.max_attempts, lease_rows.heartbeat_at, lease_rows.deadline_at, lease_rows.attempted_at ) $cte$, p_schema ); END IF; v_claim_runtime := to_regprocedure(format( '%I.claim_ready_runtime(text,bigint,double precision,double precision)', p_schema )); IF v_claim_runtime IS NOT NULL AND ( position('receipt_id' IN pg_get_function_result(v_claim_runtime::oid)) = 0 OR position('claim_batch_id' IN pg_get_function_result(v_claim_runtime::oid)) = 0 OR position('claim_batch_index' IN pg_get_function_result(v_claim_runtime::oid)) = 0 OR position('lane_drained' IN pg_get_function_result(v_claim_runtime::oid)) = 0 ) THEN EXECUTE format( 'DROP FUNCTION %I.claim_ready_runtime(TEXT, BIGINT, DOUBLE PRECISION, DOUBLE PRECISION)', p_schema ); END IF; EXECUTE format( $create_runtime$ CREATE OR REPLACE FUNCTION %1$I.claim_ready_runtime( p_queue TEXT, p_max_batch BIGINT, p_deadline_secs DOUBLE PRECISION, p_aging_secs DOUBLE PRECISION ) RETURNS TABLE( ready_slot INT, ready_generation BIGINT, lane_seq BIGINT, enqueue_shard SMALLINT, lease_slot INT, lease_generation BIGINT, claim_slot INT, receipt_id BIGINT, claim_batch_id BIGINT, claim_batch_index INT, job_id BIGINT, kind TEXT, queue TEXT, args JSONB, lane_priority SMALLINT, priority SMALLINT, attempt SMALLINT, run_lease BIGINT, max_attempts SMALLINT, run_at TIMESTAMPTZ, heartbeat_at TIMESTAMPTZ, deadline_at TIMESTAMPTZ, attempted_at TIMESTAMPTZ, created_at TIMESTAMPTZ, unique_key BYTEA, unique_states TEXT, payload JSONB, lane_drained BOOLEAN) LANGUAGE plpgsql SET search_path = pg_catalog, awa, public AS $func$ DECLARE v_lane_priority SMALLINT; v_lane_shard SMALLINT; v_claim_seq_name TEXT; v_lane_claim_seq BIGINT; v_lane_next_seq BIGINT; v_claim_limit BIGINT; v_claimed_count BIGINT; v_target_slot INT; v_target_generation BIGINT; v_target_next_lane_seq BIGINT; v_head_job_id BIGINT; v_head_run_lease BIGINT; v_head_lane_seq BIGINT; v_claimed_at TIMESTAMPTZ; v_deadline_at TIMESTAMPTZ; v_head_attempt_spent BOOLEAN; v_spent_next_seq BIGINT; v_evidence_next_seq BIGINT; BEGIN SELECT claims.priority, claims.enqueue_shard, claims.seq_name, cursors.claim_seq, cursors.next_seq, candidate.ready_slot, candidate.ready_generation, candidate.next_lane_seq INTO v_lane_priority, v_lane_shard, v_claim_seq_name, v_lane_claim_seq, v_lane_next_seq, v_target_slot, v_target_generation, v_target_next_lane_seq FROM %1$I.queue_claim_heads AS claims JOIN %1$I.queue_enqueue_heads AS enqueues ON enqueues.queue = claims.queue AND enqueues.priority = claims.priority AND enqueues.enqueue_shard = claims.enqueue_shard CROSS JOIN LATERAL ( SELECT %1$I.sequence_next_value(claims.seq_name) AS claim_seq, %1$I.sequence_next_value(enqueues.seq_name) AS next_seq ) AS cursors LEFT JOIN LATERAL ( WITH first_segment AS MATERIALIZED ( SELECT segment.ready_slot, segment.ready_generation, segment.first_run_at FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = claims.priority AND segment.enqueue_shard = claims.enqueue_shard AND segment.next_lane_seq > cursors.claim_seq -- Ready segments are non-overlapping and visibility-ordered -- (aborted sequence reservations can leave gaps, so they are -- not strictly contiguous). The smallest next_lane_seq > -- claim_seq is therefore the next segment covering or after -- the cursor; the later ready_entries lookup validates the -- target row, so a gap just falls through to the next real -- entry rather than emitting phantom work. Ordering by -- next_lane_seq lets the -- (queue, priority, enqueue_shard, next_lane_seq, ...) index -- short-circuit at LIMIT 1 instead of materialising and -- sorting the whole tail (which grows with the claim cursor). ORDER BY segment.next_lane_seq ASC LIMIT 1 ) SELECT first_segment.ready_slot, first_segment.ready_generation, slot_bound.next_lane_seq, first_segment.first_run_at AS run_at FROM first_segment CROSS JOIN LATERAL ( SELECT max(segment.next_lane_seq)::bigint AS next_lane_seq FROM %1$I.ready_segments AS segment WHERE segment.ready_slot = first_segment.ready_slot AND segment.ready_generation = first_segment.ready_generation AND segment.queue = p_queue AND segment.priority = claims.priority AND segment.enqueue_shard = claims.enqueue_shard ) AS slot_bound ) AS segment_candidate ON TRUE CROSS JOIN LATERAL ( SELECT segment_candidate.ready_slot AS ready_slot, segment_candidate.ready_generation AS ready_generation, segment_candidate.next_lane_seq AS next_lane_seq, segment_candidate.run_at AS run_at ) AS candidate WHERE claims.queue = p_queue AND NOT EXISTS ( SELECT 1 FROM awa.queue_meta AS meta WHERE meta.queue = p_queue AND meta.paused = TRUE ) AND cursors.claim_seq < cursors.next_seq ORDER BY CASE WHEN candidate.run_at IS NULL THEN NULL::smallint WHEN p_aging_secs > 0 THEN GREATEST( 1, claims.priority - FLOOR( EXTRACT(EPOCH FROM (clock_timestamp() - candidate.run_at)) / p_aging_secs )::smallint )::smallint ELSE claims.priority END ASC NULLS LAST, candidate.run_at ASC NULLS LAST, claims.priority ASC LIMIT 1 FOR UPDATE OF claims SKIP LOCKED; IF NOT FOUND THEN RETURN; END IF; -- The head lock can be granted after the statement above took its -- snapshot, and a transaction that moved rows between slots and -- committed in between is not visible to it. Resolve the target -- again in a fresh statement, with the lock held. SELECT segment.ready_slot, segment.ready_generation INTO v_target_slot, v_target_generation FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = v_lane_priority AND segment.enqueue_shard = v_lane_shard AND segment.next_lane_seq > v_lane_claim_seq ORDER BY segment.next_lane_seq ASC LIMIT 1; IF v_target_slot IS NULL THEN SELECT segment.ready_slot, segment.ready_generation, slot_bound.next_lane_seq INTO v_target_slot, v_target_generation, v_target_next_lane_seq FROM ( SELECT segment.ready_slot, segment.ready_generation, segment.first_lane_seq FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = v_lane_priority AND segment.enqueue_shard = v_lane_shard AND segment.next_lane_seq > v_lane_claim_seq -- Order by next_lane_seq (non-overlapping segments, so this -- is the next segment covering or after the cursor) for the -- index short-circuit; see the inline routing probe above. ORDER BY segment.next_lane_seq ASC LIMIT 1 ) AS segment CROSS JOIN LATERAL ( SELECT max(later_segment.next_lane_seq)::bigint AS next_lane_seq FROM %1$I.ready_segments AS later_segment WHERE later_segment.ready_slot = segment.ready_slot AND later_segment.ready_generation = segment.ready_generation AND later_segment.queue = p_queue AND later_segment.priority = v_lane_priority AND later_segment.enqueue_shard = v_lane_shard ) AS slot_bound; END IF; IF v_target_slot IS NULL THEN -- No committed ready segment is visible yet. The enqueue -- sequence may include uncommitted reservations, so do not -- advance the claim cursor. RETURN; END IF; -- Catch the lane cursor up over committed claim evidence. Every -- attempt batch was emitted by a claim that started at a cursor -- already covered by evidence and recorded the contiguous rows -- it took, so the largest recorded next_lane_seq is a safe -- cursor position whether or not the claiming runtime's -- post-commit advance ever ran. Reading only committed rows -- keeps an abort of this transaction from stranding live work. SELECT max(attempts.next_lane_seq) INTO v_evidence_next_seq FROM %1$I.ready_claim_attempt_batches AS attempts WHERE attempts.ready_slot = v_target_slot AND attempts.ready_generation = v_target_generation AND attempts.queue = p_queue AND attempts.priority = v_lane_priority AND attempts.enqueue_shard = v_lane_shard AND attempts.next_lane_seq > v_lane_claim_seq; IF v_evidence_next_seq IS NOT NULL THEN PERFORM %1$I.set_sequence_next(v_claim_seq_name, v_evidence_next_seq); v_lane_claim_seq := v_evidence_next_seq; v_target_slot := NULL; SELECT segment.ready_slot, segment.ready_generation, slot_bound.next_lane_seq INTO v_target_slot, v_target_generation, v_target_next_lane_seq FROM ( SELECT segment.ready_slot, segment.ready_generation, segment.first_lane_seq FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = v_lane_priority AND segment.enqueue_shard = v_lane_shard AND segment.next_lane_seq > v_lane_claim_seq -- Order by next_lane_seq (non-overlapping segments, so this -- is the next segment covering or after the cursor) for the -- index short-circuit; see the inline routing probe above. ORDER BY segment.next_lane_seq ASC LIMIT 1 ) AS segment CROSS JOIN LATERAL ( SELECT max(later_segment.next_lane_seq)::bigint AS next_lane_seq FROM %1$I.ready_segments AS later_segment WHERE later_segment.ready_slot = segment.ready_slot AND later_segment.ready_generation = segment.ready_generation AND later_segment.queue = p_queue AND later_segment.priority = v_lane_priority AND later_segment.enqueue_shard = v_lane_shard ) AS slot_bound; IF v_target_slot IS NULL THEN RETURN; END IF; END IF; SELECT ready.job_id, ready.run_lease, ready.lane_seq INTO v_head_job_id, v_head_run_lease, v_head_lane_seq FROM %1$I.ready_entries AS ready WHERE ready.queue = p_queue AND ready.priority = v_lane_priority AND ready.enqueue_shard = v_lane_shard AND ready.ready_slot = v_target_slot AND ready.ready_generation = v_target_generation AND ready.lane_seq >= v_lane_claim_seq -- Rows of this slot at or after the next segment of another -- slot are out of reach of this claim, whether to take or to -- move the cursor to. -- This reads one row, and every segment holds a row, so the -- first row at or after the cursor lies in the first segment -- past it when that is in this slot, and the second segment is -- all that is needed to see where another slot begins. AND ready.lane_seq < COALESCE(( SELECT min(bounding.first_lane_seq) FROM ( SELECT segment.ready_slot, segment.ready_generation, segment.first_lane_seq FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = v_lane_priority AND segment.enqueue_shard = v_lane_shard AND segment.next_lane_seq > v_lane_claim_seq ORDER BY segment.next_lane_seq ASC LIMIT 2 ) AS bounding WHERE (bounding.ready_slot, bounding.ready_generation) IS DISTINCT FROM (v_target_slot, v_target_generation) ), 9223372036854775807) ORDER BY ready.lane_seq ASC LIMIT 1; IF NOT FOUND THEN -- The segment row is committed by the same transaction as -- the ready rows, so this should only happen during a rolling -- upgrade or after manual catalog damage. Keep the claim -- cursor conservative rather than advancing over unseen work. RETURN; END IF; -- A later committed ready row proves earlier reservations are -- permanently absent: reserve_enqueue_seq holds the per-lane -- transaction advisory lock until commit/abort. Move TO the first -- visible row, never past it, so this sequence change is safe even -- if the claim aborts. Otherwise a gap before a tombstone can keep -- the bounded spent-prefix window empty on every future poll. IF v_head_lane_seq > v_lane_claim_seq THEN PERFORM %1$I.set_sequence_next(v_claim_seq_name, v_head_lane_seq); v_lane_claim_seq := v_head_lane_seq; END IF; -- The claim head stays a cold lane registry: the ready -- slot/generation is resolved from ready_segments on every claim -- rather than cached back onto this row. Caching it here -- re-introduced a per-claim UPDATE whose dead tuples could not be -- reclaimed under a pinned MVCC snapshot, making queue_claim_heads -- the dominant dead-tuple accumulator during a long-running -- transaction. The ready_segments scan above is the sole routing -- source now. v_claim_limit := LEAST(GREATEST(v_lane_next_seq - v_lane_claim_seq, 0), p_max_batch); IF v_claim_limit <= 0 THEN RETURN; END IF; v_claimed_at := clock_timestamp(); IF p_deadline_secs > 0 THEN v_deadline_at := v_claimed_at + make_interval(secs => p_deadline_secs); ELSE v_deadline_at := NULL::timestamptz; END IF; SELECT EXISTS ( SELECT 1 FROM %1$I.ready_tombstones AS tomb WHERE tomb.ready_slot = v_target_slot AND tomb.ready_generation = v_target_generation AND tomb.queue = p_queue AND tomb.priority = v_lane_priority AND tomb.enqueue_shard = v_lane_shard AND tomb.lane_seq = v_head_lane_seq LIMIT 1 ) INTO v_head_attempt_spent; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.ready_claim_attempt_batches AS existing_attempts WHERE existing_attempts.ready_slot = v_target_slot AND existing_attempts.ready_generation = v_target_generation AND existing_attempts.queue = p_queue AND existing_attempts.priority = v_lane_priority AND existing_attempts.enqueue_shard = v_lane_shard AND existing_attempts.first_lane_seq <= v_head_lane_seq AND existing_attempts.next_lane_seq > v_head_lane_seq AND existing_attempts.lane_ranges @> int8range(v_head_lane_seq, v_head_lane_seq + 1, '[)') LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent AND NOT %3$L::boolean THEN SELECT EXISTS ( SELECT 1 FROM %1$I.lease_claims AS existing_claims WHERE existing_claims.job_id = v_head_job_id AND existing_claims.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.lease_claim_closures AS existing_closures WHERE existing_closures.job_id = v_head_job_id AND existing_closures.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.receipt_completion_batches AS existing_batches WHERE existing_batches.ready_slot = v_target_slot AND existing_batches.ready_generation = v_target_generation AND existing_batches.queue = p_queue AND existing_batches.priority = v_lane_priority AND existing_batches.enqueue_shard = v_lane_shard AND existing_batches.job_ids @> ARRAY[v_head_job_id]::bigint[] AND EXISTS ( SELECT 1 FROM unnest( existing_batches.job_ids, existing_batches.run_leases ) AS completed(job_id, run_lease) WHERE completed.job_id = v_head_job_id AND completed.run_lease = v_head_run_lease + 1 ) LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.leases AS existing_leases WHERE existing_leases.job_id = v_head_job_id AND existing_leases.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.done_entries AS existing_done WHERE existing_done.job_id = v_head_job_id AND existing_done.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.deferred_jobs AS existing_deferred WHERE existing_deferred.job_id = v_head_job_id AND existing_deferred.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.dlq_entries AS existing_dlq WHERE existing_dlq.job_id = v_head_job_id AND existing_dlq.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; IF NOT v_head_attempt_spent THEN SELECT EXISTS ( SELECT 1 FROM %1$I.ready_entries AS existing_ready WHERE existing_ready.job_id = v_head_job_id AND existing_ready.run_lease = v_head_run_lease + 1 LIMIT 1 ) INTO v_head_attempt_spent; END IF; END IF; IF COALESCE(v_head_attempt_spent, FALSE) THEN WITH selected AS ( SELECT ready.job_id, ready.run_lease, ready.lane_seq, EXISTS ( SELECT 1 FROM %1$I.ready_tombstones AS tomb WHERE tomb.ready_slot = v_target_slot AND tomb.ready_generation = v_target_generation AND tomb.queue = ready.queue AND tomb.priority = ready.priority AND tomb.enqueue_shard = ready.enqueue_shard AND tomb.lane_seq = ready.lane_seq -- Keep this bounded claim on indexed probes, not a full-partition hash. OFFSET 0 ) AS is_tombstone FROM %1$I.ready_entries AS ready WHERE ready.queue = p_queue AND ready.priority = v_lane_priority AND ready.enqueue_shard = v_lane_shard AND ready.ready_slot = v_target_slot AND ready.ready_generation = v_target_generation AND ready.lane_seq >= v_lane_claim_seq ORDER BY ready.lane_seq ASC LIMIT v_claim_limit ), selected_with_spent AS ( SELECT selected.*, ( selected.is_tombstone OR EXISTS ( SELECT 1 FROM %1$I.ready_claim_attempt_batches AS existing_attempts WHERE existing_attempts.ready_slot = v_target_slot AND existing_attempts.ready_generation = v_target_generation AND existing_attempts.queue = p_queue AND existing_attempts.priority = v_lane_priority AND existing_attempts.enqueue_shard = v_lane_shard AND existing_attempts.first_lane_seq <= selected.lane_seq AND existing_attempts.next_lane_seq > selected.lane_seq AND existing_attempts.lane_ranges @> int8range(selected.lane_seq, selected.lane_seq + 1, '[)') ) OR ( NOT %3$L::boolean AND ( EXISTS ( SELECT 1 FROM %1$I.lease_claims AS existing_claims WHERE existing_claims.job_id = selected.job_id AND existing_claims.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.lease_claim_closures AS existing_closures WHERE existing_closures.job_id = selected.job_id AND existing_closures.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.receipt_completion_batches AS existing_batches WHERE existing_batches.ready_slot = v_target_slot AND existing_batches.ready_generation = v_target_generation AND existing_batches.queue = p_queue AND existing_batches.priority = v_lane_priority AND existing_batches.enqueue_shard = v_lane_shard AND existing_batches.job_ids @> ARRAY[selected.job_id]::bigint[] AND EXISTS ( SELECT 1 FROM unnest( existing_batches.job_ids, existing_batches.run_leases ) AS completed(job_id, run_lease) WHERE completed.job_id = selected.job_id AND completed.run_lease = selected.run_lease + 1 ) ) OR EXISTS ( SELECT 1 FROM %1$I.leases AS existing_leases WHERE existing_leases.job_id = selected.job_id AND existing_leases.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.done_entries AS existing_done WHERE existing_done.job_id = selected.job_id AND existing_done.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.deferred_jobs AS existing_deferred WHERE existing_deferred.job_id = selected.job_id AND existing_deferred.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.dlq_entries AS existing_dlq WHERE existing_dlq.job_id = selected.job_id AND existing_dlq.run_lease = selected.run_lease + 1 ) OR EXISTS ( SELECT 1 FROM %1$I.ready_entries AS existing_ready WHERE existing_ready.job_id = selected.job_id AND existing_ready.run_lease = selected.run_lease + 1 ) ) ) ) AS attempt_spent FROM selected ), spent_prefix AS ( SELECT selected_with_spent.lane_seq, count(*) FILTER (WHERE NOT selected_with_spent.attempt_spent) OVER (ORDER BY selected_with_spent.lane_seq) AS unspent_through FROM selected_with_spent ) SELECT LEAST( max(spent_prefix.lane_seq) + 1, ( SELECT min(other.first_lane_seq) FROM %1$I.ready_segments AS other WHERE other.queue = p_queue AND other.priority = v_lane_priority AND other.enqueue_shard = v_lane_shard AND other.next_lane_seq > v_lane_claim_seq AND other.next_lane_seq <= max(spent_prefix.lane_seq) AND (other.ready_slot, other.ready_generation) IS DISTINCT FROM (v_target_slot, v_target_generation) ) ) INTO v_spent_next_seq FROM spent_prefix WHERE unspent_through = 0; IF v_spent_next_seq IS NOT NULL THEN -- Safe in-transaction sequence movement: only skip the -- leading run of committed rows with already-committed -- spent evidence, and the rolled-back reservations before -- and between them. Every enqueue reserves its lane_seq -- through reserve_enqueue_seq, which holds the lane's -- reservation lock until the enqueue ends, so a committed -- row follows only ended reservations. A path that -- writes ready rows from any other allocation (such as -- the enqueue-head trigger) would break this. A position -- outside this generation's window can still hold a -- committed row of another generation (a producer whose -- snapshot predates a ring rotation), so the prefix stops -- at the first segment of another generation that ends -- inside it; segments are contiguous per enqueue and -- never span a position of this generation. The next -- claim targets that segment. Later -- spent/tombstoned lanes cannot move the -- cursor past an earlier live row, because the surrounding -- claim transaction could still abort. PERFORM %1$I.set_sequence_next(v_claim_seq_name, v_spent_next_seq); END IF; -- The spent-prefix path is a recovery/maintenance path for -- stale claim cursors, tombstones, or already-emitted -- attempts. Return after moving the cursor so the common -- claim query can stay narrow: it only needs to filter -- ready_tombstones and does not plan every terminal evidence -- relation on every hot-path claim. RETURN; END IF; -- The slot functions carry the claim CTE; the mode marker below -- keeps the substrate reinstall loops' receipts detection working. %2$s RETURN QUERY EXECUTE format( 'SELECT * FROM %%I.claim_ready_slot_%%s($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)', %1$L, v_target_slot ) USING p_queue, v_target_slot, v_target_generation, v_lane_priority, v_lane_shard, v_lane_claim_seq, v_claim_limit, p_aging_secs, v_claimed_at, v_deadline_at, p_deadline_secs, v_lane_next_seq; GET DIAGNOSTICS v_claimed_count = ROW_COUNT; -- If a target ready row existed but the claim CTE produced no -- rows, the spent-attempt pre-pass may still have moved the -- sequence cursor over committed spent attempts. It deliberately -- does not advance over unspent rows: newly emitted claims still -- move the sequence only after the surrounding transaction -- commits, because sequence movement is non-transactional and -- cannot be recovered by rollback. IF v_claimed_count = 0 THEN RETURN; END IF; END; $func$ $create_runtime$, p_schema, CASE WHEN p_lease_claim_receipts THEN format('-- receipts mode: claim_ready_slot_N runs INSERT INTO %I.lease_claim_batches', p_schema) ELSE format('-- legacy mode: claim_ready_slot_N runs INSERT INTO %I.leases', p_schema) END, p_lease_claim_receipts ); EXECUTE format( 'COMMENT ON FUNCTION %I.claim_ready_runtime(TEXT, BIGINT, DOUBLE PRECISION, DOUBLE PRECISION) IS %L', p_schema, 'Queue-storage claim allocator. Claims committed ready lanes, skips spent/tombstoned lanes, and leaves claim-cursor advancement safe under transaction rollback.' ); -------------------------------------------------------------------- -- Replica identity for the append-only delta tables, which have no -- primary key. PostgreSQL refuses UPDATE and DELETE on a published -- table without a replica identity, so a `FOR ALL TABLES` or -- `FOR TABLES IN SCHEMA` publication would break the rollup fold and -- prune. FULL costs nothing on INSERT or TRUNCATE, which is all the -- hot path does to these tables. Partitions never inherit the -- parent's setting, so each child is set here as well; the parent is -- set for `publish_via_partition_root` publications. -------------------------------------------------------------------- FOR v_identity_rel IN SELECT c.oid::regclass FROM pg_class AS c JOIN pg_namespace AS n ON n.oid = c.relnamespace WHERE n.nspname = p_schema AND c.relkind IN ('r', 'p') AND c.relreplident <> 'f' AND c.relname ~ '^queue_terminal_(count_deltas(_[0-9]+)?|rollup_deltas)$' ORDER BY c.relname LOOP EXECUTE format('ALTER TABLE %s REPLICA IDENTITY FULL', v_identity_rel); END LOOP; -------------------------------------------------------------------- -- Per-queue-slot claim bodies. Each addresses its own ring children -- directly, so the statement plans against one child (no Append over -- the partitioned parents), goes generic after a few executions, and -- is invalidated only when that child is truncated. -------------------------------------------------------------------- FOR v_slot IN 0..(p_queue_slot_count - 1) LOOP EXECUTE format( $create_slot$ CREATE OR REPLACE FUNCTION %1$I.claim_ready_slot_%4$s( p_queue TEXT, p_target_slot INT, p_target_generation BIGINT, p_lane_priority SMALLINT, p_lane_shard SMALLINT, p_lane_claim_seq BIGINT, p_claim_limit BIGINT, p_aging_secs DOUBLE PRECISION, p_claimed_at TIMESTAMPTZ, p_deadline_at TIMESTAMPTZ, p_deadline_secs DOUBLE PRECISION, p_lane_next_seq BIGINT ) RETURNS TABLE( ready_slot INT, ready_generation BIGINT, lane_seq BIGINT, enqueue_shard SMALLINT, lease_slot INT, lease_generation BIGINT, claim_slot INT, receipt_id BIGINT, claim_batch_id BIGINT, claim_batch_index INT, job_id BIGINT, kind TEXT, queue TEXT, args JSONB, lane_priority SMALLINT, priority SMALLINT, attempt SMALLINT, run_lease BIGINT, max_attempts SMALLINT, run_at TIMESTAMPTZ, heartbeat_at TIMESTAMPTZ, deadline_at TIMESTAMPTZ, attempted_at TIMESTAMPTZ, created_at TIMESTAMPTZ, unique_key BYTEA, unique_states TEXT, payload JSONB, lane_drained BOOLEAN) LANGUAGE plpgsql SET search_path = pg_catalog, awa, public AS $func$ DECLARE v_lane_shard SMALLINT := p_lane_shard; v_claimed_at TIMESTAMPTZ := p_claimed_at; v_deadline_at TIMESTAMPTZ := p_deadline_at; BEGIN RETURN QUERY WITH lease_ring AS MATERIALIZED ( -- #371: current lease cursor via the authority resolver -- (columns in compat mode, max-generation ledger row in -- ledger mode). MATERIALIZED pins it to a single evaluation: -- this single-reference CTE would otherwise be inlined and -- re-run the resolver once per claimed row (loops=N) on the -- inner side of the final CROSS JOIN. The pre-ledger -- lease_ring_state singleton was one cached read, so per-row -- re-execution regressed claim yield; materialized, loops=1. SELECT slot AS lease_slot, generation AS lease_generation FROM %1$I.ring_cursor('lease') ), selected AS ( SELECT ready.ready_slot, ready.ready_generation, ready.job_id, ready.kind, ready.queue, ready.args, ready.priority AS lane_priority, CASE WHEN p_aging_secs > 0 THEN GREATEST( 1, ready.priority - FLOOR( EXTRACT(EPOCH FROM (clock_timestamp() - ready.run_at)) / p_aging_secs )::smallint )::smallint ELSE ready.priority END AS effective_priority, ready.attempt, ready.run_lease, ready.max_attempts, ready.lane_seq, ready.run_at, ready.created_at, ready.unique_key, ready.unique_states, COALESCE(ready.payload, '{}'::jsonb) AS payload, EXISTS ( SELECT 1 FROM %1$I.ready_tombstones_%4$s AS tomb WHERE tomb.ready_slot = p_target_slot AND tomb.ready_generation = p_target_generation AND tomb.queue = ready.queue AND tomb.priority = ready.priority AND tomb.enqueue_shard = ready.enqueue_shard AND tomb.lane_seq = ready.lane_seq -- Keep this bounded claim on indexed probes, not a full-partition hash. OFFSET 0 ) AS is_tombstone FROM %1$I.ready_entries_%4$s AS ready WHERE ready.queue = p_queue AND ready.priority = p_lane_priority AND ready.enqueue_shard = p_lane_shard AND ready.ready_slot = p_target_slot AND ready.ready_generation = p_target_generation AND ready.lane_seq >= p_lane_claim_seq -- Stop below the next segment of another slot, from the -- same snapshot as the rows; see claim_ready_runtime. AND ready.lane_seq < COALESCE(( SELECT min(bounding.first_lane_seq) FROM ( SELECT segment.ready_slot, segment.ready_generation, segment.first_lane_seq FROM %1$I.ready_segments AS segment WHERE segment.queue = p_queue AND segment.priority = p_lane_priority AND segment.enqueue_shard = p_lane_shard AND segment.next_lane_seq > p_lane_claim_seq ORDER BY segment.next_lane_seq ASC LIMIT GREATEST(p_claim_limit, 0) + 1 ) AS bounding WHERE (bounding.ready_slot, bounding.ready_generation) IS DISTINCT FROM (p_target_slot, p_target_generation) ), 9223372036854775807) ORDER BY ready.lane_seq ASC LIMIT p_claim_limit ), selected_with_spent AS ( SELECT selected.*, selected.is_tombstone AS attempt_spent FROM selected ), %2$s SELECT claimed.ready_slot, claimed.ready_generation, claimed.lane_seq, p_lane_shard AS enqueue_shard, lease_ring.lease_slot, lease_ring.lease_generation, claimed.claim_slot, claimed.receipt_id, claimed.claim_batch_id, claimed.claim_batch_index, selected.job_id, selected.kind, selected.queue, selected.args, selected.lane_priority, selected.effective_priority, claimed.attempt, claimed.run_lease, claimed.max_attempts, selected.run_at, CASE WHEN p_deadline_secs > 0 THEN p_claimed_at ELSE NULL::timestamptz END AS heartbeat_at, p_deadline_at AS deadline_at, CASE WHEN p_deadline_secs > 0 THEN p_claimed_at ELSE NULL::timestamptz END AS attempted_at, selected.created_at, selected.unique_key, selected.unique_states, selected.payload, (p_lane_claim_seq + p_claim_limit >= p_lane_next_seq) AS lane_drained FROM claimed CROSS JOIN lease_ring JOIN selected ON selected.ready_slot = claimed.ready_slot AND selected.ready_generation = claimed.ready_generation AND selected.queue = claimed.queue AND selected.effective_priority = claimed.priority AND selected.lane_seq = claimed.lane_seq ORDER BY selected.lane_seq ASC; END; $func$ $create_slot$, p_schema, replace( v_claimed_cte, format('%I.ready_claim_attempt_batches', p_schema), format('%I.ready_claim_attempt_batches_%s', p_schema, v_slot) ), p_lease_claim_receipts, v_slot ); END LOOP; -------------------------------------------------------------------- -- Seed ring-slot rows. These are row-lock targets (and, for the -- claim ring, rescue-cursor holders); per-slot generations are -- derived from the rotation ledger (#371). -------------------------------------------------------------------- FOR v_slot IN 0..(p_queue_slot_count - 1) LOOP EXECUTE format( 'INSERT INTO %I.queue_ring_slots (slot, generation) VALUES (%s, -1) ON CONFLICT (slot) DO NOTHING', p_schema, v_slot ); END LOOP; FOR v_slot IN 0..(p_lease_slot_count - 1) LOOP EXECUTE format( 'INSERT INTO %I.lease_ring_slots (slot, generation) VALUES (%s, -1) ON CONFLICT (slot) DO NOTHING', p_schema, v_slot ); END LOOP; FOR v_slot IN 0..(p_claim_slot_count - 1) LOOP EXECUTE format( 'INSERT INTO %I.claim_ring_slots (slot, generation) VALUES (%s, -1) ON CONFLICT (slot) DO NOTHING', p_schema, v_slot ); END LOOP; PERFORM awa.refresh_ring_generation_floor_helper(p_schema); PERFORM awa.pin_function_search_paths(p_schema); END; $install$; COMMENT ON FUNCTION awa.install_queue_storage_substrate(TEXT, INT, INT, INT, BOOLEAN) IS 'Installs the queue-storage substrate (sequences, ring-state singletons, partitioned ready/tombstone/done/lease tables, lane indexes, claim_ready_runtime()) into the named schema. The default ''awa'' substrate is migration-owned and default-shaped: lease_claim_receipts=TRUE and (queue=16, lease=8, claim=8). Operators wanting non-default slot counts or lease_claim_receipts=FALSE must use a custom queue-storage schema. SECURITY INVOKER, takes a per-schema advisory xact lock. See #308.'; REVOKE EXECUTE ON FUNCTION awa.install_queue_storage_substrate(TEXT, INT, INT, INT, BOOLEAN) FROM PUBLIC;