From f8db211cf487cb1de0132c93637aaf0a87c28cb5 Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 30 Sep 2026 04:34:23 +0000 Subject: [PATCH 1/4] feat(task-queue): add Procrastinate 3.10.0 and its vendored schema (revision 174) Adds psycopg[binary,pool] and procrastinate==3.10.0. Revision 174 runs the literal output of 'procrastinate schema --read' at 3.10.0, vendored under migrations/procrastinate/, on the raw driver cursor. It never asks the installed library for a schema, so the revision stays stable across future Procrastinate upgrades, which vendor pre/post files as new revisions. TASK_QUEUE_DB_ROLE, when set, is granted DML on the queue tables only, so workers cannot change the schema. procrastinate 3.10.0 is younger than the repo's 7-day exclude-newer cooldown; a dated exclude-newer-package entry admits exactly that release and can be dropped once it ages past the window. OHE-3417 (Track 1, T1.3) Co-authored-by: openhands --- migrations/procrastinate/03.10.00_schema.sql | 599 ++++++++++++++++++ .../versions/174_add_procrastinate_schema.py | 83 +++ pyproject.toml | 4 +- tests/postgres_testdb.py | 18 +- ...test_migration_174_procrastinate_schema.py | 226 +++++++ uv.lock | 116 +++- 6 files changed, 1037 insertions(+), 9 deletions(-) create mode 100644 migrations/procrastinate/03.10.00_schema.sql create mode 100644 migrations/versions/174_add_procrastinate_schema.py create mode 100644 tests/unit/test_migration_174_procrastinate_schema.py diff --git a/migrations/procrastinate/03.10.00_schema.sql b/migrations/procrastinate/03.10.00_schema.sql new file mode 100644 index 0000000000..cd07fe49cd --- /dev/null +++ b/migrations/procrastinate/03.10.00_schema.sql @@ -0,0 +1,599 @@ +-- Procrastinate Schema + +DO $$ +BEGIN + CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog; +EXCEPTION + WHEN OTHERS THEN + -- On managed PostgreSQL services (e.g. Azure Database for PostgreSQL, Amazon RDS, + -- Google Cloud SQL), CREATE EXTENSION may fail with various error codes: + -- insufficient_privilege, feature_not_supported, or provider-specific errors. + -- Before ignoring, verify the extension actually exists — if it does not exist + -- and cannot be created, re-raise so the failure is explicit. + IF EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'plpgsql') THEN + RAISE NOTICE 'plpgsql extension already exists, skipping creation.'; + ELSE + RAISE; + END IF; +END; +$$; + +-- Enums + +CREATE TYPE procrastinate_job_status AS ENUM ( + 'todo', -- The job is queued + 'doing', -- The job has been fetched by a worker + 'succeeded', -- The job ended successfully + 'failed', -- The job ended with an error + 'cancelled', -- The job was cancelled + 'aborting', -- legacy, not used anymore since v3.0.0 + 'aborted' -- The job was aborted +); + +CREATE TYPE procrastinate_job_event_type AS ENUM ( + 'deferred', -- Job created, in todo + 'started', -- todo -> doing + 'deferred_for_retry', -- doing -> todo + 'failed', -- doing -> failed + 'succeeded', -- doing -> succeeded + 'cancelled', -- todo -> cancelled + 'abort_requested', -- not a state transition, but set in a separate field + 'aborted', -- doing -> aborted (only allowed when abort_requested field is set) + 'scheduled', -- not a state transition, but recording when a task is scheduled for + 'retried' -- Manually retried failed job +); + +-- Composite Types + +CREATE TYPE procrastinate_job_to_defer_v1 AS ( + queue_name character varying, + task_name character varying, + priority integer, + lock text, + queueing_lock text, + args jsonb, + scheduled_at timestamp with time zone +); + +-- Tables + +CREATE TABLE procrastinate_workers( + id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY, + last_heartbeat timestamp with time zone NOT NULL DEFAULT NOW() +); + +CREATE TABLE procrastinate_jobs ( + id bigserial PRIMARY KEY, + queue_name character varying(128) NOT NULL, + task_name character varying(128) NOT NULL, + priority integer DEFAULT 0 NOT NULL, + lock text, + queueing_lock text, + args jsonb DEFAULT '{}' NOT NULL, + status procrastinate_job_status DEFAULT 'todo'::procrastinate_job_status NOT NULL, + scheduled_at timestamp with time zone NULL, + attempts integer DEFAULT 0 NOT NULL, + abort_requested boolean DEFAULT false NOT NULL, + worker_id bigint REFERENCES procrastinate_workers(id) ON DELETE SET NULL, + CONSTRAINT check_not_todo_abort_requested CHECK (NOT (status = 'todo' AND abort_requested = true)) +); + +CREATE TABLE procrastinate_periodic_defers ( + id bigserial PRIMARY KEY, + task_name character varying(128) NOT NULL, + defer_timestamp bigint, + job_id bigint REFERENCES procrastinate_jobs(id) NULL, + periodic_id character varying(128) NOT NULL DEFAULT '', + CONSTRAINT procrastinate_periodic_defers_unique UNIQUE (task_name, periodic_id, defer_timestamp) +); + +CREATE TABLE procrastinate_events ( + id bigserial PRIMARY KEY, + job_id bigint NOT NULL REFERENCES procrastinate_jobs ON DELETE CASCADE, + type procrastinate_job_event_type, + at timestamp with time zone DEFAULT NOW() NULL +); + +-- Constraints & Indices + +-- this prevents from having several jobs with the same queueing lock in the "todo" state +CREATE UNIQUE INDEX procrastinate_jobs_queueing_lock_idx_v1 ON procrastinate_jobs (queueing_lock) WHERE status = 'todo'; +-- this prevents from having several jobs with the same lock in the "doing" state +CREATE UNIQUE INDEX procrastinate_jobs_lock_idx_v1 ON procrastinate_jobs (lock) WHERE status = 'doing'; + +-- Index for select_stalled_jobs_by_heartbeat query +CREATE INDEX idx_procrastinate_jobs_worker_not_null ON procrastinate_jobs(worker_id) WHERE worker_id IS NOT NULL AND status = 'doing'::procrastinate_job_status; + +CREATE INDEX procrastinate_jobs_queue_name_idx_v1 ON procrastinate_jobs(queue_name); +CREATE INDEX procrastinate_jobs_id_lock_idx_v1 ON procrastinate_jobs (id, lock) WHERE status = ANY (ARRAY['todo'::procrastinate_job_status, 'doing'::procrastinate_job_status]); +CREATE INDEX procrastinate_jobs_priority_idx_v1 ON procrastinate_jobs(priority desc, id asc) WHERE (status = 'todo'::procrastinate_job_status); + +CREATE INDEX procrastinate_events_job_id_fkey_v1 ON procrastinate_events(job_id); + +CREATE INDEX procrastinate_periodic_defers_job_id_fkey_v1 ON procrastinate_periodic_defers(job_id); + +CREATE INDEX idx_procrastinate_workers_last_heartbeat ON procrastinate_workers(last_heartbeat); + +-- Functions +CREATE FUNCTION procrastinate_defer_jobs_v1( + jobs procrastinate_job_to_defer_v1[] +) + RETURNS bigint[] + LANGUAGE plpgsql +AS $$ +DECLARE + job_ids bigint[]; +BEGIN + WITH inserted_jobs AS ( + INSERT INTO procrastinate_jobs (queue_name, task_name, priority, lock, queueing_lock, args, scheduled_at) + SELECT (job).queue_name, + (job).task_name, + (job).priority, + (job).lock, + (job).queueing_lock, + (job).args, + (job).scheduled_at + FROM unnest(jobs) AS job + RETURNING id + ) + SELECT array_agg(id) FROM inserted_jobs INTO job_ids; + + RETURN job_ids; +END; +$$; + +CREATE FUNCTION procrastinate_defer_periodic_job_v2( + _queue_name character varying, + _lock character varying, + _queueing_lock character varying, + _task_name character varying, + _priority integer, + _periodic_id character varying, + _defer_timestamp bigint, + _args jsonb +) + RETURNS bigint + LANGUAGE plpgsql +AS $$ +DECLARE + _job_id bigint; + _defer_id bigint; +BEGIN + INSERT + INTO procrastinate_periodic_defers (task_name, periodic_id, defer_timestamp) + VALUES (_task_name, _periodic_id, _defer_timestamp) + ON CONFLICT DO NOTHING + RETURNING id into _defer_id; + + IF _defer_id IS NULL THEN + RETURN NULL; + END IF; + + UPDATE procrastinate_periodic_defers + SET job_id = ( + SELECT COALESCE(( + SELECT unnest(procrastinate_defer_jobs_v1( + ARRAY[ + ROW( + _queue_name, + _task_name, + _priority, + _lock, + _queueing_lock, + _args, + NULL::timestamptz + ) + ]::procrastinate_job_to_defer_v1[] + )) + ), NULL) + ) + WHERE id = _defer_id + RETURNING job_id INTO _job_id; + + DELETE + FROM procrastinate_periodic_defers + USING ( + SELECT id + FROM procrastinate_periodic_defers + WHERE procrastinate_periodic_defers.task_name = _task_name + AND procrastinate_periodic_defers.periodic_id = _periodic_id + AND procrastinate_periodic_defers.defer_timestamp < _defer_timestamp + ORDER BY id + FOR UPDATE + ) to_delete + WHERE procrastinate_periodic_defers.id = to_delete.id; + + RETURN _job_id; +END; +$$; + +CREATE FUNCTION procrastinate_fetch_job_v2( + target_queue_names character varying[], + p_worker_id bigint +) + RETURNS procrastinate_jobs + LANGUAGE plpgsql +AS $$ +DECLARE + found_jobs procrastinate_jobs; +BEGIN + WITH candidate AS ( + SELECT jobs.* + FROM procrastinate_jobs AS jobs + WHERE + -- reject the job if its lock has earlier or higher priority jobs + NOT EXISTS ( + SELECT 1 + FROM procrastinate_jobs AS other_jobs + WHERE + jobs.lock IS NOT NULL + AND other_jobs.lock = jobs.lock + AND ( + -- job with same lock is already running + other_jobs.status = 'doing' + OR + -- job with same lock is waiting and has higher priority (or same priority but was queued first) + ( + other_jobs.status = 'todo' + AND ( + other_jobs.priority > jobs.priority + OR ( + other_jobs.priority = jobs.priority + AND other_jobs.id < jobs.id + ) + ) + ) + ) + ) + AND jobs.status = 'todo' + AND (target_queue_names IS NULL OR jobs.queue_name = ANY( target_queue_names )) + AND (jobs.scheduled_at IS NULL OR jobs.scheduled_at <= now()) + ORDER BY jobs.priority DESC, jobs.id ASC LIMIT 1 + FOR UPDATE OF jobs SKIP LOCKED + ) + UPDATE procrastinate_jobs + SET status = 'doing', worker_id = p_worker_id + FROM candidate + WHERE procrastinate_jobs.id = candidate.id + RETURNING procrastinate_jobs.* INTO found_jobs; + + RETURN found_jobs; +END; +$$; + +CREATE FUNCTION procrastinate_finish_job_v1(job_id bigint, end_status procrastinate_job_status, delete_job boolean) + RETURNS void + LANGUAGE plpgsql +AS $$ +DECLARE + _job_id bigint; +BEGIN + IF end_status NOT IN ('succeeded', 'failed', 'aborted') THEN + RAISE 'End status should be either "succeeded", "failed" or "aborted" (job id: %)', job_id; + END IF; + IF delete_job THEN + DELETE FROM procrastinate_jobs + WHERE id = job_id AND status IN ('todo', 'doing') + RETURNING id INTO _job_id; + ELSE + UPDATE procrastinate_jobs + SET status = end_status, + abort_requested = false, + attempts = CASE status + WHEN 'doing' THEN attempts + 1 ELSE attempts + END + WHERE id = job_id AND status IN ('todo', 'doing') + RETURNING id INTO _job_id; + END IF; + IF _job_id IS NULL THEN + RAISE 'Job was not found or not in "doing" or "todo" status (job id: %)', job_id; + END IF; +END; +$$; + +CREATE FUNCTION procrastinate_cancel_job_v1(job_id bigint, abort boolean, delete_job boolean) + RETURNS bigint + LANGUAGE plpgsql +AS $$ +DECLARE + _job_id bigint; +BEGIN + IF delete_job THEN + DELETE FROM procrastinate_jobs + WHERE id = job_id AND status = 'todo' + RETURNING id INTO _job_id; + END IF; + IF _job_id IS NULL THEN + IF abort THEN + UPDATE procrastinate_jobs + SET abort_requested = true, + status = CASE status + WHEN 'todo' THEN 'cancelled'::procrastinate_job_status ELSE status + END + WHERE id = job_id AND status IN ('todo', 'doing') + RETURNING id INTO _job_id; + ELSE + UPDATE procrastinate_jobs + SET status = 'cancelled'::procrastinate_job_status + WHERE id = job_id AND status = 'todo' + RETURNING id INTO _job_id; + END IF; + END IF; + RETURN _job_id; +END; +$$; + +CREATE FUNCTION procrastinate_retry_job_v1( + job_id bigint, + retry_at timestamp with time zone, + new_priority integer, + new_queue_name character varying, + new_lock character varying +) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE + _job_id bigint; + _abort_requested boolean; +BEGIN + SELECT abort_requested FROM procrastinate_jobs + WHERE id = job_id AND status = 'doing' + FOR UPDATE + INTO _abort_requested; + IF _abort_requested THEN + UPDATE procrastinate_jobs + SET status = 'failed'::procrastinate_job_status + WHERE id = job_id AND status = 'doing' + RETURNING id INTO _job_id; + ELSE + UPDATE procrastinate_jobs + SET status = 'todo'::procrastinate_job_status, + attempts = attempts + 1, + scheduled_at = retry_at, + priority = COALESCE(new_priority, priority), + queue_name = COALESCE(new_queue_name, queue_name), + lock = COALESCE(new_lock, lock) + WHERE id = job_id AND status = 'doing' + RETURNING id INTO _job_id; + END IF; + + IF _job_id IS NULL THEN + RAISE 'Job was not found or not in "doing" status (job id: %)', job_id; + END IF; +END; +$$; + +CREATE FUNCTION procrastinate_retry_job_v2( + job_id bigint, + retry_at timestamp with time zone, + new_priority integer, + new_queue_name character varying, + new_lock character varying +) RETURNS void LANGUAGE plpgsql AS $$ +DECLARE + _job_id bigint; + _abort_requested boolean; + _current_status procrastinate_job_status; +BEGIN + SELECT status, abort_requested FROM procrastinate_jobs + WHERE id = job_id AND status IN ('doing', 'failed') + FOR UPDATE + INTO _current_status, _abort_requested; + IF _current_status = 'doing' AND _abort_requested THEN + UPDATE procrastinate_jobs + SET status = 'failed'::procrastinate_job_status + WHERE id = job_id AND status = 'doing' + RETURNING id INTO _job_id; + ELSE + UPDATE procrastinate_jobs + SET status = 'todo'::procrastinate_job_status, + attempts = attempts + 1, + scheduled_at = retry_at, + priority = COALESCE(new_priority, priority), + queue_name = COALESCE(new_queue_name, queue_name), + lock = COALESCE(new_lock, lock) + WHERE id = job_id AND status IN ('doing', 'failed') + RETURNING id INTO _job_id; + END IF; + + IF _job_id IS NULL THEN + RAISE 'Job was not found or has an invalid status to retry (job id: %)', job_id; + END IF; + +END; +$$; + +CREATE FUNCTION procrastinate_notify_queue_job_inserted_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +DECLARE + payload TEXT; +BEGIN + SELECT json_build_object('type', 'job_inserted', 'job_id', NEW.id)::text INTO payload; + PERFORM pg_notify('procrastinate_queue_v1#' || NEW.queue_name, payload); + PERFORM pg_notify('procrastinate_any_queue_v1', payload); + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_notify_queue_abort_job_v1() +RETURNS trigger + LANGUAGE plpgsql +AS $$ +DECLARE + payload TEXT; +BEGIN + SELECT json_build_object('type', 'abort_job_requested', 'job_id', NEW.id)::text INTO payload; + PERFORM pg_notify('procrastinate_queue_v1#' || NEW.queue_name, payload); + PERFORM pg_notify('procrastinate_any_queue_v1', payload); + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_trigger_function_status_events_insert_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO procrastinate_events(job_id, type) + VALUES (NEW.id, 'deferred'::procrastinate_job_event_type); + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_trigger_function_status_events_update_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +BEGIN + WITH t AS ( + SELECT CASE + WHEN OLD.status = 'todo'::procrastinate_job_status + AND NEW.status = 'doing'::procrastinate_job_status + THEN 'started'::procrastinate_job_event_type + WHEN OLD.status = 'doing'::procrastinate_job_status + AND NEW.status = 'todo'::procrastinate_job_status + THEN 'deferred_for_retry'::procrastinate_job_event_type + WHEN OLD.status = 'doing'::procrastinate_job_status + AND NEW.status = 'failed'::procrastinate_job_status + THEN 'failed'::procrastinate_job_event_type + WHEN OLD.status = 'doing'::procrastinate_job_status + AND NEW.status = 'succeeded'::procrastinate_job_status + THEN 'succeeded'::procrastinate_job_event_type + WHEN OLD.status = 'todo'::procrastinate_job_status + AND ( + NEW.status = 'cancelled'::procrastinate_job_status + OR NEW.status = 'failed'::procrastinate_job_status + OR NEW.status = 'succeeded'::procrastinate_job_status + ) + THEN 'cancelled'::procrastinate_job_event_type + WHEN OLD.status = 'doing'::procrastinate_job_status + AND NEW.status = 'aborted'::procrastinate_job_status + THEN 'aborted'::procrastinate_job_event_type + WHEN OLD.status = 'failed'::procrastinate_job_status + AND NEW.status = 'todo'::procrastinate_job_status + THEN 'retried'::procrastinate_job_event_type + ELSE NULL + END as event_type + ) + INSERT INTO procrastinate_events(job_id, type) + SELECT NEW.id, t.event_type + FROM t + WHERE t.event_type IS NOT NULL; + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_trigger_function_scheduled_events_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO procrastinate_events(job_id, type, at) + VALUES (NEW.id, 'scheduled'::procrastinate_job_event_type, NEW.scheduled_at); + + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_trigger_abort_requested_events_procedure_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +BEGIN + INSERT INTO procrastinate_events(job_id, type) + VALUES (NEW.id, 'abort_requested'::procrastinate_job_event_type); + RETURN NEW; +END; +$$; + +CREATE FUNCTION procrastinate_unlink_periodic_defers_v1() + RETURNS trigger + LANGUAGE plpgsql +AS $$ +BEGIN + UPDATE procrastinate_periodic_defers + SET job_id = NULL + WHERE job_id = OLD.id; + RETURN OLD; +END; +$$; + +CREATE FUNCTION procrastinate_register_worker_v1() + RETURNS TABLE(worker_id bigint) + LANGUAGE plpgsql +AS $$ +BEGIN + RETURN QUERY + INSERT INTO procrastinate_workers DEFAULT VALUES + RETURNING procrastinate_workers.id; +END; +$$; + +CREATE FUNCTION procrastinate_unregister_worker_v1(worker_id bigint) + RETURNS void + LANGUAGE plpgsql +AS $$ +BEGIN + DELETE FROM procrastinate_workers + WHERE id = worker_id; +END; +$$; + +CREATE FUNCTION procrastinate_update_heartbeat_v1(worker_id bigint) + RETURNS void + LANGUAGE plpgsql +AS $$ +BEGIN + UPDATE procrastinate_workers + SET last_heartbeat = NOW() + WHERE id = worker_id; +END; +$$; + +CREATE FUNCTION procrastinate_prune_stalled_workers_v1(seconds_since_heartbeat float) + RETURNS TABLE(worker_id bigint) + LANGUAGE plpgsql +AS $$ +BEGIN + RETURN QUERY + DELETE FROM procrastinate_workers + WHERE last_heartbeat < NOW() - (seconds_since_heartbeat || 'SECOND')::INTERVAL + RETURNING procrastinate_workers.id; +END; +$$; + +-- Triggers + +CREATE TRIGGER procrastinate_jobs_notify_queue_job_inserted_v1 + AFTER INSERT ON procrastinate_jobs + FOR EACH ROW WHEN ((new.status = 'todo'::procrastinate_job_status)) + EXECUTE PROCEDURE procrastinate_notify_queue_job_inserted_v1(); + +CREATE TRIGGER procrastinate_jobs_notify_queue_job_aborted_v1 + AFTER UPDATE OF abort_requested ON procrastinate_jobs + FOR EACH ROW WHEN ((old.abort_requested = false AND new.abort_requested = true AND new.status = 'doing'::procrastinate_job_status)) + EXECUTE PROCEDURE procrastinate_notify_queue_abort_job_v1(); + +CREATE TRIGGER procrastinate_trigger_status_events_update_v1 + AFTER UPDATE OF status ON procrastinate_jobs + FOR EACH ROW + EXECUTE PROCEDURE procrastinate_trigger_function_status_events_update_v1(); + +CREATE TRIGGER procrastinate_trigger_status_events_insert_v1 + AFTER INSERT ON procrastinate_jobs + FOR EACH ROW WHEN ((new.status = 'todo'::procrastinate_job_status)) + EXECUTE PROCEDURE procrastinate_trigger_function_status_events_insert_v1(); + +CREATE TRIGGER procrastinate_trigger_scheduled_events_v1 + AFTER UPDATE OR INSERT ON procrastinate_jobs + FOR EACH ROW WHEN ((new.scheduled_at IS NOT NULL AND new.status = 'todo'::procrastinate_job_status)) + EXECUTE PROCEDURE procrastinate_trigger_function_scheduled_events_v1(); + +CREATE TRIGGER procrastinate_trigger_abort_requested_events_v1 + AFTER UPDATE OF abort_requested ON procrastinate_jobs + FOR EACH ROW WHEN ((new.abort_requested = true)) + EXECUTE PROCEDURE procrastinate_trigger_abort_requested_events_procedure_v1(); + +CREATE TRIGGER procrastinate_trigger_delete_jobs_v1 + BEFORE DELETE ON procrastinate_jobs + FOR EACH ROW EXECUTE PROCEDURE procrastinate_unlink_periodic_defers_v1(); diff --git a/migrations/versions/174_add_procrastinate_schema.py b/migrations/versions/174_add_procrastinate_schema.py new file mode 100644 index 0000000000..7d536fab19 --- /dev/null +++ b/migrations/versions/174_add_procrastinate_schema.py @@ -0,0 +1,83 @@ +"""Add the Procrastinate 3.10.0 task queue schema. + +Revision ID: 174 +Revises: 173 +Create Date: 2026-09-30 00:00:00.000000 + +The DDL is the literal output of ``procrastinate schema --read`` at 3.10.0, +vendored in ``migrations/procrastinate/``. It is never generated here from the +installed library: a historical revision has to apply the same schema on every +future install, whatever Procrastinate version is installed by then. Upgrading +Procrastinate vendors the release's ``*_01_pre_*.sql`` / ``*_50_post_*.sql`` +files as new revisions; ``post`` files wait until the rollback window closes. + +The script contains ``:`` and ``%``, so it runs on the raw driver cursor with no +parameters rather than through SQLAlchemy's parameter parsing. + +``TASK_QUEUE_DB_ROLE`` names the role the task queue workers connect as. When +set, it is granted DML on the queue tables and nothing else, so workers cannot +change the schema. It must already exist. +""" + +import os +import re +from pathlib import Path +from typing import Sequence + +from alembic import op + +revision: str = '174' +down_revision: str | None = '173' +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +SCHEMA_SQL = ( + Path(__file__).resolve().parents[1] / 'procrastinate' / '03.10.00_schema.sql' +) +TABLES = ( + 'procrastinate_workers', + 'procrastinate_jobs', + 'procrastinate_periodic_defers', + 'procrastinate_events', +) +ROLE_NAME_RE = re.compile(r'^[a-z_][a-z0-9_]*$') + + +def _run_script(sql: str) -> None: + cursor = op.get_bind().connection.cursor() + try: + cursor.execute(sql) + finally: + cursor.close() + + +def _grant_worker_role(role: str) -> None: + if not ROLE_NAME_RE.match(role): + raise ValueError(f'TASK_QUEUE_DB_ROLE is not a plain role name: {role!r}') + tables = ', '.join(TABLES) + _run_script( + f'GRANT SELECT, INSERT, UPDATE, DELETE ON {tables} TO {role};\n' + 'GRANT USAGE, SELECT ON SEQUENCE procrastinate_jobs_id_seq, ' + 'procrastinate_periodic_defers_id_seq, procrastinate_events_id_seq, ' + f'procrastinate_workers_id_seq TO {role};\n' + ) + + +def upgrade() -> None: + _run_script(SCHEMA_SQL.read_text()) + role = os.getenv('TASK_QUEUE_DB_ROLE', '').strip() + if role: + _grant_worker_role(role) + + +def downgrade() -> None: + script = SCHEMA_SQL.read_text() + functions = re.findall(r'^CREATE FUNCTION (\w+)', script, re.M) + types = re.findall(r'^CREATE TYPE (\w+)', script, re.M) + # Dropping procrastinate_jobs also drops the functions returning its row + # type, hence IF EXISTS on the functions only. + _run_script( + f'DROP TABLE {", ".join(reversed(TABLES))} CASCADE;\n' + + ''.join(f'DROP FUNCTION IF EXISTS {name};\n' for name in functions) + + ''.join(f'DROP TYPE {name};\n' for name in types) + ) diff --git a/pyproject.toml b/pyproject.toml index 1ea767c08a..ebddd63749 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -70,10 +70,12 @@ dependencies = [ "pillow==12.3.0", "playwright==1.58.0", "posthog==7.9.12", + "procrastinate==3.10.0", "prometheus-client==0.24.1", "prompt-toolkit==3.0.52", "protobuf==5.29.6", # Updated to fix CVE-2026-0994 "psutil==7.2.2", + "psycopg[binary,pool]==3.3.6", "psycopg2-binary==2.9.11", "pybase62==1.0.0", "pygithub>=2.5", @@ -207,4 +209,4 @@ omit = [ "tests/*", "**/test_*" ] [tool.uv] package = false exclude-newer = "7 days" -exclude-newer-package = { openhands-agent-server = false, openhands-sdk = false, openhands-tools = false, litellm = false } +exclude-newer-package = { openhands-agent-server = false, openhands-sdk = false, openhands-tools = false, litellm = false, procrastinate = "2026-09-24T00:00:00Z" } diff --git a/tests/postgres_testdb.py b/tests/postgres_testdb.py index df42b372d7..fc6a731f26 100644 --- a/tests/postgres_testdb.py +++ b/tests/postgres_testdb.py @@ -217,6 +217,16 @@ def create_template_database(server: PostgresServer) -> str: def _run_migrations(server: PostgresServer, database: str) -> None: + run_alembic(server, database, 'upgrade', 'head') + + +def run_alembic( + server: PostgresServer, + database: str, + *args: str, + extra_env: dict[str, str] | None = None, +) -> None: + """Run ``alembic `` against ``database``.""" # Run alembic out of process: importing ``migrations/env.py`` here would # reconfigure logging for the whole pytest session (alembic.ini sets the # root logger to DEBUG). @@ -237,9 +247,11 @@ def _run_migrations(server: PostgresServer, database: str) -> None: WEB_HOST='', ) env.pop('STRIPE_API_KEY', None) + env.pop('TASK_QUEUE_DB_ROLE', None) + env.update(extra_env or {}) result = subprocess.run( - [sys.executable, '-m', 'alembic', '-c', str(ALEMBIC_INI), 'upgrade', 'head'], + [sys.executable, '-m', 'alembic', '-c', str(ALEMBIC_INI), *args], cwd=REPO_ROOT, env=env, capture_output=True, @@ -247,8 +259,8 @@ def _run_migrations(server: PostgresServer, database: str) -> None: ) if result.returncode != 0: raise PostgresUnavailableError( - 'alembic upgrade head failed while building the test database ' - f'template:\n{result.stdout}\n{result.stderr}' + f'alembic {" ".join(args)} failed on {database}:' + f'\n{result.stdout}\n{result.stderr}' ) diff --git a/tests/unit/test_migration_174_procrastinate_schema.py b/tests/unit/test_migration_174_procrastinate_schema.py new file mode 100644 index 0000000000..3704604367 --- /dev/null +++ b/tests/unit/test_migration_174_procrastinate_schema.py @@ -0,0 +1,226 @@ +"""Revision 174 installs exactly the Procrastinate 3.10.0 schema. + +The revision runs vendored SQL rather than asking the installed library for +its schema, so these tests pin the two together: the vendored file is what +3.10.0 ships, and a migrated database is indistinguishable from one Procrastinate +set up itself. +""" + +import uuid +from collections.abc import Iterator +from pathlib import Path + +import procrastinate +import psycopg +import pytest +from procrastinate.schema import SchemaManager +from sqlalchemy import create_engine, text +from sqlalchemy.engine import Engine +from sqlalchemy.pool import NullPool + +from tests import postgres_testdb + +VENDORED = ( + Path(__file__).resolve().parents[2] + / 'migrations' + / 'procrastinate' + / '03.10.00_schema.sql' +) + +CATALOG_QUERIES = { + 'columns': """ + SELECT table_name, column_name, data_type, column_default, is_nullable, + ordinal_position + FROM information_schema.columns + WHERE table_schema = 'public' AND table_name LIKE 'procrastinate%' + """, + 'indexes': """ + SELECT indexname, indexdef FROM pg_indexes + WHERE schemaname = 'public' AND tablename LIKE 'procrastinate%' + """, + 'constraints': """ + SELECT conrelid::regclass::text, conname, pg_get_constraintdef(oid) + FROM pg_constraint WHERE conrelid::regclass::text LIKE 'procrastinate%' + """, + 'functions': """ + SELECT proname, pg_get_functiondef(oid) FROM pg_proc + WHERE proname LIKE 'procrastinate%' + """, + 'triggers': """ + SELECT tgname, pg_get_triggerdef(oid) FROM pg_trigger + WHERE tgname LIKE 'procrastinate%' + """, + 'types': """ + SELECT t.typname, e.enumlabel, e.enumsortorder + FROM pg_type t LEFT JOIN pg_enum e ON e.enumtypid = t.oid + WHERE t.typname LIKE 'procrastinate%' + """, +} + + +def _catalog(engine: Engine) -> dict[str, list[tuple]]: + with engine.connect() as conn: + return { + name: sorted(tuple(row) for row in conn.execute(text(query))) + for name, query in CATALOG_QUERIES.items() + } + + +def _conninfo(server: postgres_testdb.PostgresServer, database: str, **kw) -> str: + params = dict( + host=server.host, + port=server.port, + dbname=database, + user=server.user, + password=server.password, + ) + params.update(kw) + return psycopg.conninfo.make_conninfo(**params) + + +@pytest.fixture +def fresh_database( + postgres_server: postgres_testdb.PostgresServer, +) -> Iterator[str]: + name = f'{postgres_testdb.TEST_DB_PREFIX}{uuid.uuid4().hex[:12]}' + postgres_testdb._run_admin_sql( + postgres_server, f'CREATE DATABASE "{name}" TEMPLATE template0' + ) + try: + yield name + finally: + postgres_testdb.drop_test_database(postgres_server, name) + + +def test_vendored_schema_is_the_pinned_release(): + """Bumping Procrastinate must come with new vendored migration revisions.""" + assert procrastinate.__version__ == '3.10.0', ( + 'Procrastinate was upgraded: vendor the new release migrations ' + '(procrastinate/sql/migrations/*_01_pre_*.sql and *_50_post_*.sql) as ' + 'new Alembic revisions, then update this pin. Never edit revision 174.' + ) + assert VENDORED.read_text() == SchemaManager.get_schema() + + +def test_migrated_schema_matches_a_fresh_procrastinate_install( + engine: Engine, + postgres_server: postgres_testdb.PostgresServer, + fresh_database: str, +): + with psycopg.connect( + _conninfo(postgres_server, fresh_database), autocommit=True + ) as conn: + conn.execute(SchemaManager.get_schema()) + reference = create_engine( + postgres_server.sync_url(fresh_database), poolclass=NullPool + ) + try: + expected = _catalog(reference) + finally: + reference.dispose() + + migrated = _catalog(engine) + + assert all(expected.values()) + assert migrated == expected + + +def test_downgrade_removes_every_procrastinate_object( + engine: Engine, test_database: postgres_testdb.TestDatabase +): + postgres_testdb.run_alembic( + test_database.server, test_database.name, 'downgrade', '173' + ) + assert not any(_catalog(engine).values()) + + postgres_testdb.run_alembic( + test_database.server, test_database.name, 'upgrade', 'head' + ) + assert all(_catalog(engine).values()) + + +class TestWorkerRole: + @pytest.fixture + def worker_role( + self, test_database: postgres_testdb.TestDatabase + ) -> Iterator[tuple[str, str]]: + role = f'tq_worker_{uuid.uuid4().hex[:12]}' + password = uuid.uuid4().hex + server = test_database.server + postgres_testdb._run_admin_sql( + server, f"CREATE ROLE {role} LOGIN PASSWORD '{password}'" + ) + try: + yield role, password + finally: + # Grants live in the test database, so DROP OWNED must run there. + engine = postgres_testdb._admin_engine(server, test_database.name) + try: + with engine.connect() as conn: + conn.execute(text(f'DROP OWNED BY {role} CASCADE')) + finally: + engine.dispose() + postgres_testdb._run_admin_sql(server, f'DROP ROLE {role}') + + @pytest.fixture + def worker_conninfo( + self, test_database: postgres_testdb.TestDatabase, worker_role + ) -> str: + role, password = worker_role + postgres_testdb.run_alembic( + test_database.server, test_database.name, 'downgrade', '173' + ) + postgres_testdb.run_alembic( + test_database.server, + test_database.name, + 'upgrade', + 'head', + extra_env={'TASK_QUEUE_DB_ROLE': role}, + ) + return _conninfo( + test_database.server, test_database.name, user=role, password=password + ) + + async def test_worker_role_runs_the_queue(self, worker_conninfo: str): + app = procrastinate.App( + connector=procrastinate.PsycopgConnector(conninfo=worker_conninfo) + ) + + @app.task(name='noop', queue='business') + async def noop() -> None: + return None + + async with app.open_async(): + job_id = await noop.defer_async() + await app.run_worker_async(queues=['business'], wait=False) + status = await app.job_manager.get_job_status_async(job_id) + + assert status == procrastinate.jobs.Status.SUCCEEDED + + def test_worker_role_cannot_change_the_schema(self, worker_conninfo: str): + statements = [ + 'CREATE TABLE tq_probe (id int)', + 'ALTER TABLE procrastinate_jobs ADD COLUMN probe int', + 'DROP TABLE procrastinate_events', + 'CREATE OR REPLACE FUNCTION procrastinate_register_worker_v1() ' + 'RETURNS TABLE(worker_id bigint) LANGUAGE sql AS $$ SELECT 1::bigint $$', + ] + for ddl in statements: + with psycopg.connect(worker_conninfo) as conn: + with pytest.raises(psycopg.errors.InsufficientPrivilege): + conn.execute(ddl) + + def test_rejects_role_name_that_is_not_an_identifier( + self, test_database: postgres_testdb.TestDatabase + ): + postgres_testdb.run_alembic( + test_database.server, test_database.name, 'downgrade', '173' + ) + with pytest.raises(postgres_testdb.PostgresUnavailableError): + postgres_testdb.run_alembic( + test_database.server, + test_database.name, + 'upgrade', + 'head', + extra_env={'TASK_QUEUE_DB_ROLE': 'x; DROP TABLE org'}, + ) diff --git a/uv.lock b/uv.lock index 36dd2355be..19ec7a9007 100644 --- a/uv.lock +++ b/uv.lock @@ -11,7 +11,7 @@ resolution-markers = [ ] [options] -exclude-newer = "2026-09-18T23:45:07.153448Z" +exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values. exclude-newer-span = "P7D" [options.exclude-newer-package] @@ -19,6 +19,7 @@ openhands-agent-server = false litellm = false openhands-tools = false openhands-sdk = false +procrastinate = "2026-09-24T00:00:00Z" [[package]] name = "agent-client-protocol" @@ -267,6 +268,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ed/c9/d7977eaacb9df673210491da99e6a247e93df98c715fc43fd136ce1d3d33/arrow-1.4.0-py3-none-any.whl", hash = "sha256:749f0769958ebdc79c173ff0b0670d59051a535fa26e8eba02953dc19eb43205", size = 68797, upload-time = "2025-10-18T17:46:45.663Z" }, ] +[[package]] +name = "asgiref" +version = "3.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e6/26/3b59f2bdae5f640389becb1f673cded775287f5fc4f816309d9ca9a3f93d/asgiref-3.12.1.tar.gz", hash = "sha256:59dcb51c272ad209d59bed5708a64a333083e86017d7fcdd67498eeab7784340", size = 42378, upload-time = "2026-07-14T09:56:18.087Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/1b/54f4ad77cd8a584fa70746c47df988e002cf1ee1eba43364d46f87803647/asgiref-3.12.1-py3-none-any.whl", hash = "sha256:fe386d1c2bff7259ea95929266d12a8cf9a8b5a1c2598402967d8792e7a7c094", size = 25478, upload-time = "2026-07-14T09:56:16.926Z" }, +] + [[package]] name = "asn1crypto" version = "1.5.1" @@ -808,7 +818,7 @@ name = "clr-loader" version = "0.2.10" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cffi", marker = "sys_platform == 'win32'" }, + { name = "cffi" }, ] sdist = { url = "https://files.pythonhosted.org/packages/18/24/c12faf3f61614b3131b5c98d3bf0d376b49c7feaa73edca559aeb2aee080/clr_loader-0.2.10.tar.gz", hash = "sha256:81f114afbc5005bafc5efe5af1341d400e22137e275b042a8979f3feb9fc9446", size = 83605, upload-time = "2026-01-03T23:13:06.984Z" } wheels = [ @@ -927,6 +937,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9e/ee/a4cf96b8ce1e566ed238f0659ac2d3f007ed1d14b181bcb684e19561a69a/coverage-7.13.5-py3-none-any.whl", hash = "sha256:34b02417cf070e173989b3db962f7ed56d2f644307b2cf9d5a0f258e13084a61", size = 211346, upload-time = "2026-03-17T10:33:15.691Z" }, ] +[[package]] +name = "croniter" +version = "6.2.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/37/57/2e2a65aee2a70483cb28e2b7e15a072d00a523207593b44400d4717bb100/croniter-6.2.4.tar.gz", hash = "sha256:fc124f751b1b04805c2a04b061898b436b45ab2320b045e1e052ea895de65189", size = 166267, upload-time = "2026-07-10T09:52:59.955Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cd/ba/d678e5bd329646ca51d3c92addbc77804e86d21f4b6b6a027218e6abb010/croniter-6.2.4-py3-none-any.whl", hash = "sha256:8ef3d544107a5c05a150a2d78f8bf5a8eb9c5c4d93405a736b824109574e3f4d", size = 46677, upload-time = "2026-07-10T09:52:58.425Z" }, +] + [[package]] name = "cryptography" version = "50.0.0" @@ -3588,10 +3610,12 @@ dependencies = [ { name = "pillow" }, { name = "playwright" }, { name = "posthog" }, + { name = "procrastinate" }, { name = "prometheus-client" }, { name = "prompt-toolkit" }, { name = "protobuf" }, { name = "psutil" }, + { name = "psycopg", extra = ["binary", "pool"] }, { name = "psycopg2-binary" }, { name = "pybase62" }, { name = "pygithub" }, @@ -3728,10 +3752,12 @@ requires-dist = [ { name = "pillow", specifier = "==12.3.0" }, { name = "playwright", specifier = "==1.58.0" }, { name = "posthog", specifier = "==7.9.12" }, + { name = "procrastinate", specifier = "==3.10.0" }, { name = "prometheus-client", specifier = "==0.24.1" }, { name = "prompt-toolkit", specifier = "==3.0.52" }, { name = "protobuf", specifier = "==5.29.6" }, { name = "psutil", specifier = "==7.2.2" }, + { name = "psycopg", extras = ["binary", "pool"], specifier = "==3.3.6" }, { name = "psycopg2-binary", specifier = "==2.9.11" }, { name = "pybase62", specifier = "==1.0.0" }, { name = "pygithub", specifier = ">=2.5" }, @@ -4256,6 +4282,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/88/74/a88bf1b1efeae488a0c0b7bdf71429c313722d1fc0f377537fbe554e6180/pre_commit-4.2.0-py2.py3-none-any.whl", hash = "sha256:a009ca7205f1eb497d10b845e52c838a98b6cdd2102a6c8e4540e94ee75c58bd", size = 220707, upload-time = "2025-03-18T21:35:19.343Z" }, ] +[[package]] +name = "procrastinate" +version = "3.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "asgiref" }, + { name = "attrs" }, + { name = "croniter" }, + { name = "packaging" }, + { name = "psycopg", extra = ["pool"] }, + { name = "python-dateutil" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3a/8a/ab3a9841b38b9349eb3cb871c47d0683ce4811669c9f0fb7b889343bea8f/procrastinate-3.10.0.tar.gz", hash = "sha256:3668da769088682abf91b8c760de467be1203218411872f1a26ac7515d4f980d", size = 91101, upload-time = "2026-09-23T21:22:57.59Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/52/51/c7ea18faef04260a1e67cb60c2c815ff0f2792c323c4f3a733478cbfc883/procrastinate-3.10.0-py3-none-any.whl", hash = "sha256:949ad25b4377c30e03a9d0e053d15dfa47ef02b3f12ae8a7f3254686183c152c", size = 155244, upload-time = "2026-09-23T21:22:55.873Z" }, +] + [[package]] name = "prometheus-client" version = "0.24.1" @@ -4416,6 +4460,68 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8c/c7/7bb2e321574b10df20cbde462a94e2b71d05f9bbda251ef27d104668306a/psutil-7.2.2-cp37-abi3-win_arm64.whl", hash = "sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee", size = 134617, upload-time = "2026-01-28T18:15:36.514Z" }, ] +[[package]] +name = "psycopg" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, + { name = "tzdata", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/26/3ea4ca5eaea1c0debcdf7ee7c1613fbe721dc27a03c461c0817ffd8a0601/psycopg-3.3.6.tar.gz", hash = "sha256:c081f2250df751a943036e42db6df4571c66cd0aabe8291a7a506512b12007d2", size = 168171, upload-time = "2026-09-18T13:22:55.152Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4e/de/748bd7609c71cae5d737f0ba9192f19329f70180ecda8fff3cac02c5abe3/psycopg-3.3.6-py3-none-any.whl", hash = "sha256:a1db9f7148b06a28606767efaca51fa6f9398c5c0a3810519be69d7000bdb631", size = 215490, upload-time = "2026-09-18T13:15:29.374Z" }, +] + +[package.optional-dependencies] +binary = [ + { name = "psycopg-binary", marker = "implementation_name != 'pypy'" }, +] +pool = [ + { name = "psycopg-pool" }, +] + +[[package]] +name = "psycopg-binary" +version = "3.3.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/01/2cdd1824e58b4467ee0b9498664cd28c42d8794db6b1e35b6bcb834f0044/psycopg_binary-3.3.6-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3f84dab25e0385692ee13274c68678377e0b1a70ab9d14e56264cbf61f60c62d", size = 4707086, upload-time = "2026-09-18T13:18:05.138Z" }, + { url = "https://files.pythonhosted.org/packages/f6/76/de9948ac06895261c84d5b9fbe283d8f3c5bc9f070691b8d9eaa1b51e322/psycopg_binary-3.3.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:612382ac3ed13651c7fa44b5fee9fbf7baaa2ddbc6f500391672682c5f1df9e0", size = 4769607, upload-time = "2026-09-18T13:18:12.83Z" }, + { url = "https://files.pythonhosted.org/packages/76/a9/72436c9915ee4905964689e7f0e182ce7767cc0a0390b3ce703be8177625/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:366db6e97e66b37211475f20c4c1324a2dc0dd825e46d4e87f9d599304d276f9", size = 5554134, upload-time = "2026-09-18T13:18:21.175Z" }, + { url = "https://files.pythonhosted.org/packages/0a/42/948bb3d2617795093512613fd96ba380e922992c7908fbc073858147d196/psycopg_binary-3.3.6-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1679a1cb93fbe5a6d1fd58d82cbddcc6fcb8c61446ba7cae6eb2a7b19bc585de", size = 5235723, upload-time = "2026-09-18T13:18:27.071Z" }, + { url = "https://files.pythonhosted.org/packages/99/47/93e823ff1b0088400703410939c9bda3e63ed9c850b3ee088e8769f4c10b/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:37d40450659401600e6d043ff586c89a71a69f33cbb8bcdba6cdb2569beecdbe", size = 6833587, upload-time = "2026-09-18T13:18:33.794Z" }, + { url = "https://files.pythonhosted.org/packages/5e/2d/ecc69c847795aa704041a9f5667a6b0938a088cf1853636d762a6938e493/psycopg_binary-3.3.6-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a5165300324efd5a772c48a88ab3a928513ab3979fca76553e62ee815f7b2b9c", size = 5070013, upload-time = "2026-09-18T13:18:39.628Z" }, + { url = "https://files.pythonhosted.org/packages/92/36/6126f0dac21713dcae91404f2a76da18598a6252339a8c669c46370d43b2/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d636338c8f21b0df2f84657b00bc34f9313f826ef93f1155bc743607e4a0c5eb", size = 4597367, upload-time = "2026-09-18T13:18:45.023Z" }, + { url = "https://files.pythonhosted.org/packages/4d/29/7ecfc04243b46c89ffd49924e9c5634ea904ef96c7d0f37e4073623584c1/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:a4ee3bdd5468a725f2a4d9aab8a74b6d0279f768c8b5d3aeb102c5307ff3d59c", size = 4275419, upload-time = "2026-09-18T13:18:49.299Z" }, + { url = "https://files.pythonhosted.org/packages/6e/90/2f46d2e0de79706ac170df0a3637fe63c4498fc04f131f6049520b78b806/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:289aadd6a00e151203c081f708348ec89f1e483c9b510ef4ac3981f847f01f79", size = 4007358, upload-time = "2026-09-18T13:18:53.944Z" }, + { url = "https://files.pythonhosted.org/packages/03/48/6744e91291b751a8cf12d63d719977974bb94c84ceba913e7ddb2e478e51/psycopg_binary-3.3.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f21d057f3e5f5491067e5b292498073b73847d48799b099803fef100775fcc52", size = 4320156, upload-time = "2026-09-18T13:18:59.258Z" }, + { url = "https://files.pythonhosted.org/packages/1a/9b/94ff7fce53a64d5b286e2ec454e0a025cf3d6e6b4a9189bef16aa5de98b2/psycopg_binary-3.3.6-cp312-cp312-win_amd64.whl", hash = "sha256:e23a66a763fbe83fcc210bc77c27e5a5ea380ebf091c06f34d8561b695e5a40f", size = 3658864, upload-time = "2026-09-18T13:19:06.503Z" }, + { url = "https://files.pythonhosted.org/packages/b4/c3/c072584b69ad44a747b448cfc9766fecb8aae56e372a017e2ef668790057/psycopg_binary-3.3.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:5ad8f35e67cc16d1fad1fa8c88972dc9b3a3141ea67897399904edab96a301b6", size = 4712284, upload-time = "2026-09-18T13:19:13.451Z" }, + { url = "https://files.pythonhosted.org/packages/0a/b9/4283b785339e8e2318d03048994b093d650ea6289fabaa806b765dc0d449/psycopg_binary-3.3.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:373704aea331d3f3e3402c125a1543f5875e2986ebb54f97d1647942161f803f", size = 4772031, upload-time = "2026-09-18T13:19:18.524Z" }, + { url = "https://files.pythonhosted.org/packages/6f/72/7a1321d359246769fff1affffbd0132785a28f7f63c18524c15a502398f4/psycopg_binary-3.3.6-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b82491019b884d62318b5f30706c3d7e6d4e5a6cb7eabcb3edc0c1b0fdaceae9", size = 5556392, upload-time = "2026-09-18T13:19:24.418Z" }, + { url = "https://files.pythonhosted.org/packages/de/b0/c6f8a0585a5dacbea74e130bcfc66629390e8f5bbc79d2a8e806e8952150/psycopg_binary-3.3.6-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cec5ea900390897d0b46130f60bc2883bf19c314f9044235217c8be88b0ef269", size = 5237855, upload-time = "2026-09-18T13:19:31.257Z" }, + { url = "https://files.pythonhosted.org/packages/e2/fc/c3a7a8bbef7e945ec584ac61d460a612363ea398511cd0e220242b1d69f1/psycopg_binary-3.3.6-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:98c02090d88f2ebc0ec1e8da538f77d225ce0fffecf372aa39262e62a1b054ef", size = 6833856, upload-time = "2026-09-18T13:19:43.622Z" }, + { url = "https://files.pythonhosted.org/packages/a9/f2/8e80b921db728ebb68fc105bd7c4277f908210ad755bd6481d5ea7add740/psycopg_binary-3.3.6-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ee2c4728c691245e24501fcd7a97b5b381236b9985bc445bba88cdce7d1b5784", size = 5070730, upload-time = "2026-09-18T13:19:49.968Z" }, + { url = "https://files.pythonhosted.org/packages/54/6a/5b313e0c5348244f0e973aff3258bf86766656256d5ece8d541a53e35b4a/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f19cc87343eaa55255e76b31259a570072ac95d6ae82c92dd34b97691f5e49dc", size = 4598089, upload-time = "2026-09-18T13:19:56.426Z" }, + { url = "https://files.pythonhosted.org/packages/32/e9/db7f76ec24bf6699e92bf604e5c4bae10664a681a8999ef42aa0faf0f2c6/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fdccb3a0e184b03e9baa673b15a809cf36c339c85dbda0ebc25a698846dfbee8", size = 4278481, upload-time = "2026-09-18T13:20:04.681Z" }, + { url = "https://files.pythonhosted.org/packages/61/83/72c67013656f4d6b547caabffb193e91d57e63f90eefdcc6d045c400e97d/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:9892188bb15e5803beb51afe8a25add6b56be391a53058e8bca03b74e1e6bf22", size = 4009229, upload-time = "2026-09-18T13:20:11.905Z" }, + { url = "https://files.pythonhosted.org/packages/82/35/5e4500df2c999eb0faed8b184e6958b834172128274f06167a5deef4c19c/psycopg_binary-3.3.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3af90f92769d8cc10f94515ee7a0aef36ea85ca733a0ce22858f6e0953f41138", size = 4321467, upload-time = "2026-09-18T13:20:17.949Z" }, + { url = "https://files.pythonhosted.org/packages/55/7f/e350e1cf498ba2565c3f87b12f429d2012eb86b76c2b3845a19ee5fbb4d6/psycopg_binary-3.3.6-cp313-cp313-win_amd64.whl", hash = "sha256:0ebfad5d131de9f892ae9e70cc7616207768b6714b66a52d4612b8ceaf78b372", size = 3658179, upload-time = "2026-09-18T13:20:22.691Z" }, +] + +[[package]] +name = "psycopg-pool" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/74/5e/c0664b968b102ff68b811d999c728546c48d5c1eec03e3bbaf88c0cb4472/psycopg_pool-3.3.3.tar.gz", hash = "sha256:df87b5d9d0ad7db37f6cdad4fa8ce113d250f5997f6db38e9a99192fb67f9e1d", size = 32006, upload-time = "2026-09-22T15:53:24.947Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/b4/452c6607a0f479465cd8a9b0d9956919fcb150050c1f83f9f11e6b8ee8dc/psycopg_pool-3.3.3-py3-none-any.whl", hash = "sha256:9b9cd6a4fcec47a410f7e82d408540e7f77b478509e91b44c1a5457a13e5ff37", size = 40304, upload-time = "2026-09-22T15:53:23.712Z" }, +] + [[package]] name = "psycopg2-binary" version = "2.9.11" @@ -7572,7 +7678,7 @@ name = "pythonnet" version = "3.0.5" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "clr-loader", marker = "sys_platform == 'win32'" }, + { name = "clr-loader" }, ] sdist = { url = "https://files.pythonhosted.org/packages/9a/d6/1afd75edd932306ae9bd2c2d961d603dc2b52fcec51b04afea464f1f6646/pythonnet-3.0.5.tar.gz", hash = "sha256:48e43ca463941b3608b32b4e236db92d8d40db4c58a75ace902985f76dac21cf", size = 239212, upload-time = "2024-12-13T08:30:44.393Z" } wheels = [ @@ -8158,8 +8264,8 @@ name = "secretstorage" version = "3.5.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cryptography", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, - { name = "jeepney", marker = "sys_platform != 'emscripten' and sys_platform != 'win32'" }, + { name = "cryptography" }, + { name = "jeepney" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } wheels = [ From f5ba470776bdd5e86ee1a20fa5fc2e2e7aafd3de Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 30 Sep 2026 17:04:26 +0000 Subject: [PATCH 2/4] fix(task-queue): grant the task queue role on every migration run Move the worker role's DML grants out of revision 174 into migrations/env.py, where they run after every migration run. A role created after 174 was applied, and tables or sequences added by later Procrastinate revisions, now get their grants on the next run. Rename TASK_QUEUE_DB_ROLE to TASK_QUEUE_DB_USER, the name the worker connects as, and quote the role instead of restricting it to plain identifiers. Co-authored-by: openhands --- migrations/env.py | 36 ++++++++++++- .../versions/174_add_procrastinate_schema.py | 22 +------- tests/postgres_testdb.py | 2 +- ...test_migration_174_procrastinate_schema.py | 54 ++++++++++++++----- 4 files changed, 80 insertions(+), 34 deletions(-) diff --git a/migrations/env.py b/migrations/env.py index 345376ddf8..0de7208af6 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -16,7 +16,7 @@ from alembic import context # noqa: E402 from google.cloud.sql.connector import Connector # noqa: E402 -from sqlalchemy import Engine, create_engine, text # noqa: E402 +from sqlalchemy import Connection, Engine, create_engine, text # noqa: E402 from sqlalchemy.pool import NullPool # noqa: E402 from openhands.db.ssl import build_db_url_query, build_pg8000_connect_args # noqa: E402 @@ -48,6 +48,11 @@ # CREATE DATABASE runs from here. Every PostgreSQL server has this database. MAINTENANCE_DB_NAME = 'postgres' +# The role the task queue worker connects as (server/task_queue/config.py). It +# must already exist. It gets DML on the queue tables and nothing else, so a +# worker cannot change the schema. +TASK_QUEUE_DB_USER = os.getenv('TASK_QUEUE_DB_USER', '').strip() + logger = logging.getLogger('alembic.env') @@ -117,6 +122,33 @@ def create_database_if_missing() -> None: connection.exec_driver_sql(f'CREATE DATABASE {name}') +def grant_task_queue_role(connection: Connection) -> None: + """Grant TASK_QUEUE_DB_USER DML on every Procrastinate table and sequence. + + Runs after every migration run, not in the revision that creates the tables: + the role may be set up after that revision was applied, and later + Procrastinate revisions add tables and sequences of their own. + """ + rows = connection.execute( + text( + 'SELECT relkind, quote_ident(relname) FROM pg_class' + ' WHERE relnamespace = current_schema()::regnamespace' + " AND relkind IN ('r', 'S') AND starts_with(relname, 'procrastinate_')" + ) + ).all() + tables = ', '.join(name for kind, name in rows if kind == 'r') + sequences = ', '.join(name for kind, name in rows if kind == 'S') + role = connection.dialect.identifier_preparer.quote(TASK_QUEUE_DB_USER) + if tables: + connection.exec_driver_sql( + f'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {tables} TO {role}' + ) + if sequences: + connection.exec_driver_sql( + f'GRANT USAGE, SELECT ON SEQUENCE {sequences} TO {role}' + ) + + # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config @@ -180,6 +212,8 @@ def run_migrations_online() -> None: with context.begin_transaction(): context.run_migrations() + if TASK_QUEUE_DB_USER: + grant_task_queue_role(connection) if context.is_offline_mode(): diff --git a/migrations/versions/174_add_procrastinate_schema.py b/migrations/versions/174_add_procrastinate_schema.py index 7d536fab19..d128483c6b 100644 --- a/migrations/versions/174_add_procrastinate_schema.py +++ b/migrations/versions/174_add_procrastinate_schema.py @@ -14,12 +14,10 @@ The script contains ``:`` and ``%``, so it runs on the raw driver cursor with no parameters rather than through SQLAlchemy's parameter parsing. -``TASK_QUEUE_DB_ROLE`` names the role the task queue workers connect as. When -set, it is granted DML on the queue tables and nothing else, so workers cannot -change the schema. It must already exist. +The task queue role's grants live in ``migrations/env.py`` and run on every +migration, so a role created after this revision was applied still gets them. """ -import os import re from pathlib import Path from typing import Sequence @@ -40,7 +38,6 @@ 'procrastinate_periodic_defers', 'procrastinate_events', ) -ROLE_NAME_RE = re.compile(r'^[a-z_][a-z0-9_]*$') def _run_script(sql: str) -> None: @@ -51,23 +48,8 @@ def _run_script(sql: str) -> None: cursor.close() -def _grant_worker_role(role: str) -> None: - if not ROLE_NAME_RE.match(role): - raise ValueError(f'TASK_QUEUE_DB_ROLE is not a plain role name: {role!r}') - tables = ', '.join(TABLES) - _run_script( - f'GRANT SELECT, INSERT, UPDATE, DELETE ON {tables} TO {role};\n' - 'GRANT USAGE, SELECT ON SEQUENCE procrastinate_jobs_id_seq, ' - 'procrastinate_periodic_defers_id_seq, procrastinate_events_id_seq, ' - f'procrastinate_workers_id_seq TO {role};\n' - ) - - def upgrade() -> None: _run_script(SCHEMA_SQL.read_text()) - role = os.getenv('TASK_QUEUE_DB_ROLE', '').strip() - if role: - _grant_worker_role(role) def downgrade() -> None: diff --git a/tests/postgres_testdb.py b/tests/postgres_testdb.py index fc6a731f26..104e0030ce 100644 --- a/tests/postgres_testdb.py +++ b/tests/postgres_testdb.py @@ -247,7 +247,7 @@ def run_alembic( WEB_HOST='', ) env.pop('STRIPE_API_KEY', None) - env.pop('TASK_QUEUE_DB_ROLE', None) + env.pop('TASK_QUEUE_DB_USER', None) env.update(extra_env or {}) result = subprocess.run( diff --git a/tests/unit/test_migration_174_procrastinate_schema.py b/tests/unit/test_migration_174_procrastinate_schema.py index 3704604367..b8afb82504 100644 --- a/tests/unit/test_migration_174_procrastinate_schema.py +++ b/tests/unit/test_migration_174_procrastinate_schema.py @@ -144,11 +144,13 @@ class TestWorkerRole: def worker_role( self, test_database: postgres_testdb.TestDatabase ) -> Iterator[tuple[str, str]]: - role = f'tq_worker_{uuid.uuid4().hex[:12]}' + # Not a plain identifier, so the grants only work if the role is quoted. + role = f'TQ-worker {uuid.uuid4().hex[:12]}' + quoted = f'"{role}"' password = uuid.uuid4().hex server = test_database.server postgres_testdb._run_admin_sql( - server, f"CREATE ROLE {role} LOGIN PASSWORD '{password}'" + server, f"CREATE ROLE {quoted} LOGIN PASSWORD '{password}'" ) try: yield role, password @@ -157,25 +159,24 @@ def worker_role( engine = postgres_testdb._admin_engine(server, test_database.name) try: with engine.connect() as conn: - conn.execute(text(f'DROP OWNED BY {role} CASCADE')) + conn.execute(text(f'DROP OWNED BY {quoted} CASCADE')) finally: engine.dispose() - postgres_testdb._run_admin_sql(server, f'DROP ROLE {role}') + postgres_testdb._run_admin_sql(server, f'DROP ROLE {quoted}') @pytest.fixture def worker_conninfo( self, test_database: postgres_testdb.TestDatabase, worker_role ) -> str: + # The test database is already at head, so this run applies no revision: + # the role is granted even though it did not exist when 174 ran. role, password = worker_role - postgres_testdb.run_alembic( - test_database.server, test_database.name, 'downgrade', '173' - ) postgres_testdb.run_alembic( test_database.server, test_database.name, 'upgrade', 'head', - extra_env={'TASK_QUEUE_DB_ROLE': role}, + extra_env={'TASK_QUEUE_DB_USER': role}, ) return _conninfo( test_database.server, test_database.name, user=role, password=password @@ -210,17 +211,46 @@ def test_worker_role_cannot_change_the_schema(self, worker_conninfo: str): with pytest.raises(psycopg.errors.InsufficientPrivilege): conn.execute(ddl) - def test_rejects_role_name_that_is_not_an_identifier( - self, test_database: postgres_testdb.TestDatabase + def test_grants_procrastinate_objects_added_after_174( + self, engine: Engine, test_database: postgres_testdb.TestDatabase, worker_role ): + role, _ = worker_role + with engine.begin() as conn: + conn.execute(text('CREATE TABLE procrastinate_probe (id bigserial)')) + postgres_testdb.run_alembic( - test_database.server, test_database.name, 'downgrade', '173' + test_database.server, + test_database.name, + 'upgrade', + 'head', + extra_env={'TASK_QUEUE_DB_USER': role}, ) + + with engine.connect() as conn: + # A comma-separated privilege list is true if any one is held. + granted = ( + conn.execute( + text( + "SELECT bool_and(has_table_privilege(:role, 'procrastinate_probe', p))" + " FROM unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE']) p" + ' UNION ALL SELECT has_sequence_privilege(' + ":role, 'procrastinate_probe_id_seq', 'USAGE')" + ), + {'role': role}, + ) + .scalars() + .all() + ) + assert granted == [True, True] + + def test_migration_fails_when_the_role_does_not_exist( + self, test_database: postgres_testdb.TestDatabase + ): with pytest.raises(postgres_testdb.PostgresUnavailableError): postgres_testdb.run_alembic( test_database.server, test_database.name, 'upgrade', 'head', - extra_env={'TASK_QUEUE_DB_ROLE': 'x; DROP TABLE org'}, + extra_env={'TASK_QUEUE_DB_USER': f'missing_{uuid.uuid4().hex[:12]}'}, ) From 3e13d8ee1b079c973829c036b5652f27f7b35a31 Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 30 Sep 2026 20:53:26 +0000 Subject: [PATCH 3/4] refactor(task-queue): drop the restricted queue role The worker process runs the job bodies in-process, and those use the app engine and DB_USER, so the process holds full privileges regardless. A DML-only role on the queue connection alongside it is not a privilege boundary, and nothing in the chart, KOTS or saas-deploy ever set TASK_QUEUE_DB_USER, so the grant never ran. Remove the grant from migrations/env.py, which reverts that file to main, along with the role's tests and the test-only extra_env hook. Co-authored-by: openhands --- migrations/env.py | 36 +----- .../versions/174_add_procrastinate_schema.py | 3 - tests/postgres_testdb.py | 9 +- ...test_migration_174_procrastinate_schema.py | 121 ------------------ 4 files changed, 2 insertions(+), 167 deletions(-) diff --git a/migrations/env.py b/migrations/env.py index 0de7208af6..345376ddf8 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -16,7 +16,7 @@ from alembic import context # noqa: E402 from google.cloud.sql.connector import Connector # noqa: E402 -from sqlalchemy import Connection, Engine, create_engine, text # noqa: E402 +from sqlalchemy import Engine, create_engine, text # noqa: E402 from sqlalchemy.pool import NullPool # noqa: E402 from openhands.db.ssl import build_db_url_query, build_pg8000_connect_args # noqa: E402 @@ -48,11 +48,6 @@ # CREATE DATABASE runs from here. Every PostgreSQL server has this database. MAINTENANCE_DB_NAME = 'postgres' -# The role the task queue worker connects as (server/task_queue/config.py). It -# must already exist. It gets DML on the queue tables and nothing else, so a -# worker cannot change the schema. -TASK_QUEUE_DB_USER = os.getenv('TASK_QUEUE_DB_USER', '').strip() - logger = logging.getLogger('alembic.env') @@ -122,33 +117,6 @@ def create_database_if_missing() -> None: connection.exec_driver_sql(f'CREATE DATABASE {name}') -def grant_task_queue_role(connection: Connection) -> None: - """Grant TASK_QUEUE_DB_USER DML on every Procrastinate table and sequence. - - Runs after every migration run, not in the revision that creates the tables: - the role may be set up after that revision was applied, and later - Procrastinate revisions add tables and sequences of their own. - """ - rows = connection.execute( - text( - 'SELECT relkind, quote_ident(relname) FROM pg_class' - ' WHERE relnamespace = current_schema()::regnamespace' - " AND relkind IN ('r', 'S') AND starts_with(relname, 'procrastinate_')" - ) - ).all() - tables = ', '.join(name for kind, name in rows if kind == 'r') - sequences = ', '.join(name for kind, name in rows if kind == 'S') - role = connection.dialect.identifier_preparer.quote(TASK_QUEUE_DB_USER) - if tables: - connection.exec_driver_sql( - f'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {tables} TO {role}' - ) - if sequences: - connection.exec_driver_sql( - f'GRANT USAGE, SELECT ON SEQUENCE {sequences} TO {role}' - ) - - # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config @@ -212,8 +180,6 @@ def run_migrations_online() -> None: with context.begin_transaction(): context.run_migrations() - if TASK_QUEUE_DB_USER: - grant_task_queue_role(connection) if context.is_offline_mode(): diff --git a/migrations/versions/174_add_procrastinate_schema.py b/migrations/versions/174_add_procrastinate_schema.py index d128483c6b..6354e70f4e 100644 --- a/migrations/versions/174_add_procrastinate_schema.py +++ b/migrations/versions/174_add_procrastinate_schema.py @@ -13,9 +13,6 @@ The script contains ``:`` and ``%``, so it runs on the raw driver cursor with no parameters rather than through SQLAlchemy's parameter parsing. - -The task queue role's grants live in ``migrations/env.py`` and run on every -migration, so a role created after this revision was applied still gets them. """ import re diff --git a/tests/postgres_testdb.py b/tests/postgres_testdb.py index 104e0030ce..ba949d1b6a 100644 --- a/tests/postgres_testdb.py +++ b/tests/postgres_testdb.py @@ -220,12 +220,7 @@ def _run_migrations(server: PostgresServer, database: str) -> None: run_alembic(server, database, 'upgrade', 'head') -def run_alembic( - server: PostgresServer, - database: str, - *args: str, - extra_env: dict[str, str] | None = None, -) -> None: +def run_alembic(server: PostgresServer, database: str, *args: str) -> None: """Run ``alembic `` against ``database``.""" # Run alembic out of process: importing ``migrations/env.py`` here would # reconfigure logging for the whole pytest session (alembic.ini sets the @@ -247,8 +242,6 @@ def run_alembic( WEB_HOST='', ) env.pop('STRIPE_API_KEY', None) - env.pop('TASK_QUEUE_DB_USER', None) - env.update(extra_env or {}) result = subprocess.run( [sys.executable, '-m', 'alembic', '-c', str(ALEMBIC_INI), *args], diff --git a/tests/unit/test_migration_174_procrastinate_schema.py b/tests/unit/test_migration_174_procrastinate_schema.py index b8afb82504..d60ca46166 100644 --- a/tests/unit/test_migration_174_procrastinate_schema.py +++ b/tests/unit/test_migration_174_procrastinate_schema.py @@ -6,12 +6,8 @@ set up itself. """ -import uuid -from collections.abc import Iterator from pathlib import Path -import procrastinate -import psycopg import pytest from procrastinate.schema import SchemaManager from sqlalchemy import create_engine, text @@ -137,120 +133,3 @@ def test_downgrade_removes_every_procrastinate_object( test_database.server, test_database.name, 'upgrade', 'head' ) assert all(_catalog(engine).values()) - - -class TestWorkerRole: - @pytest.fixture - def worker_role( - self, test_database: postgres_testdb.TestDatabase - ) -> Iterator[tuple[str, str]]: - # Not a plain identifier, so the grants only work if the role is quoted. - role = f'TQ-worker {uuid.uuid4().hex[:12]}' - quoted = f'"{role}"' - password = uuid.uuid4().hex - server = test_database.server - postgres_testdb._run_admin_sql( - server, f"CREATE ROLE {quoted} LOGIN PASSWORD '{password}'" - ) - try: - yield role, password - finally: - # Grants live in the test database, so DROP OWNED must run there. - engine = postgres_testdb._admin_engine(server, test_database.name) - try: - with engine.connect() as conn: - conn.execute(text(f'DROP OWNED BY {quoted} CASCADE')) - finally: - engine.dispose() - postgres_testdb._run_admin_sql(server, f'DROP ROLE {quoted}') - - @pytest.fixture - def worker_conninfo( - self, test_database: postgres_testdb.TestDatabase, worker_role - ) -> str: - # The test database is already at head, so this run applies no revision: - # the role is granted even though it did not exist when 174 ran. - role, password = worker_role - postgres_testdb.run_alembic( - test_database.server, - test_database.name, - 'upgrade', - 'head', - extra_env={'TASK_QUEUE_DB_USER': role}, - ) - return _conninfo( - test_database.server, test_database.name, user=role, password=password - ) - - async def test_worker_role_runs_the_queue(self, worker_conninfo: str): - app = procrastinate.App( - connector=procrastinate.PsycopgConnector(conninfo=worker_conninfo) - ) - - @app.task(name='noop', queue='business') - async def noop() -> None: - return None - - async with app.open_async(): - job_id = await noop.defer_async() - await app.run_worker_async(queues=['business'], wait=False) - status = await app.job_manager.get_job_status_async(job_id) - - assert status == procrastinate.jobs.Status.SUCCEEDED - - def test_worker_role_cannot_change_the_schema(self, worker_conninfo: str): - statements = [ - 'CREATE TABLE tq_probe (id int)', - 'ALTER TABLE procrastinate_jobs ADD COLUMN probe int', - 'DROP TABLE procrastinate_events', - 'CREATE OR REPLACE FUNCTION procrastinate_register_worker_v1() ' - 'RETURNS TABLE(worker_id bigint) LANGUAGE sql AS $$ SELECT 1::bigint $$', - ] - for ddl in statements: - with psycopg.connect(worker_conninfo) as conn: - with pytest.raises(psycopg.errors.InsufficientPrivilege): - conn.execute(ddl) - - def test_grants_procrastinate_objects_added_after_174( - self, engine: Engine, test_database: postgres_testdb.TestDatabase, worker_role - ): - role, _ = worker_role - with engine.begin() as conn: - conn.execute(text('CREATE TABLE procrastinate_probe (id bigserial)')) - - postgres_testdb.run_alembic( - test_database.server, - test_database.name, - 'upgrade', - 'head', - extra_env={'TASK_QUEUE_DB_USER': role}, - ) - - with engine.connect() as conn: - # A comma-separated privilege list is true if any one is held. - granted = ( - conn.execute( - text( - "SELECT bool_and(has_table_privilege(:role, 'procrastinate_probe', p))" - " FROM unnest(ARRAY['SELECT', 'INSERT', 'UPDATE', 'DELETE']) p" - ' UNION ALL SELECT has_sequence_privilege(' - ":role, 'procrastinate_probe_id_seq', 'USAGE')" - ), - {'role': role}, - ) - .scalars() - .all() - ) - assert granted == [True, True] - - def test_migration_fails_when_the_role_does_not_exist( - self, test_database: postgres_testdb.TestDatabase - ): - with pytest.raises(postgres_testdb.PostgresUnavailableError): - postgres_testdb.run_alembic( - test_database.server, - test_database.name, - 'upgrade', - 'head', - extra_env={'TASK_QUEUE_DB_USER': f'missing_{uuid.uuid4().hex[:12]}'}, - ) From 5c0444013f2576b5b3365c6a29c0772fb0bdbf06 Mon Sep 17 00:00:00 2001 From: Ai Vong Date: Wed, 30 Sep 2026 16:06:35 -0500 Subject: [PATCH 4/4] fix(test): add missing imports in procrastinate schema test Adds the imports the test already relies on (procrastinate, psycopg, psycopg.conninfo, uuid, collections.abc.Iterator) to fix ruff F821 undefined-name failures in the Lint python check. Co-authored-by: openhands --- tests/unit/test_migration_174_procrastinate_schema.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/unit/test_migration_174_procrastinate_schema.py b/tests/unit/test_migration_174_procrastinate_schema.py index d60ca46166..81aa6d2a4b 100644 --- a/tests/unit/test_migration_174_procrastinate_schema.py +++ b/tests/unit/test_migration_174_procrastinate_schema.py @@ -6,8 +6,13 @@ set up itself. """ +import uuid +from collections.abc import Iterator from pathlib import Path +import procrastinate +import psycopg +import psycopg.conninfo import pytest from procrastinate.schema import SchemaManager from sqlalchemy import create_engine, text