Skip to content

feat(task-queue): PLTF-3689 add Procrastinate and its database schema - #587

Merged
aivong-openhands merged 7 commits into
mainfrom
task-queue/02-procrastinate-schema
Sep 30, 2026
Merged

aivong-openhands merged 7 commits into
mainfrom
task-queue/02-procrastinate-schema

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

The task queue needs its Postgres schema before any worker can run. This adds Procrastinate and migration 174, which creates its four tables, functions, triggers and types on every install. Nothing enqueues or runs jobs yet, so the new tables sit empty until a worker is added.

Migration 174 runs a copy of the SQL that Procrastinate 3.10.0 ships, checked into the repo, instead of asking the installed library for its schema. That way the migration builds the same schema on every future install, whatever Procrastinate version is installed by then, and a later upgrade adds its changes as new migrations.

Summary

  • Adds procrastinate==3.10.0 and psycopg[binary,pool] (psycopg 3, which Procrastinate's async connector needs) to the project dependencies.
  • Adds migration 174, which runs the vendored migrations/procrastinate/03.10.00_schema.sql.
  • When TASK_QUEUE_DB_USER (the role the worker connects as) is set, migrations/env.py grants it read and write access to every procrastinate_* table and sequence, but no permission to change the schema. It does this after every migration run, not inside revision 174, so a role created after 174 was applied, or a table added by a later Procrastinate upgrade, is granted on the next run.
  • Adds a dated exclude-newer-package entry so uv accepts Procrastinate 3.10.0, which is newer than the repo's 7-day cooldown on new releases. The entry can be removed once the release is older than the cooldown.

Issue Number

OHE-3417

How to Test

uv run pytest tests/unit/test_migration_174_procrastinate_schema.py (the Python Tests on Linux CI job also runs it). The tests check that:

  • the vendored SQL is byte-identical to the schema Procrastinate 3.10.0 ships, and a pinned version check fails if Procrastinate is upgraded without new migrations;
  • a migrated database has the same columns, indexes, constraints, functions, triggers and types as one Procrastinate set up itself;
  • downgrading to 173 removes every Procrastinate object, and upgrading again restores them;
  • a role set through TASK_QUEUE_DB_USER on a database already at head (so no revision runs) can run a job end to end but gets a permission error on DDL; a procrastinate_* table added later is granted on the next run; the role name is quoted (the test role's name contains a space and a hyphen); and a role that does not exist fails the migration.

Video/Screenshots

N/A. No UI change.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

If TASK_QUEUE_DB_USER is set, the role must already exist when migrations run, or the GRANT fails and the whole migration run rolls back. When it is unset, nothing is granted.


This PR was drafted by an AI agent on behalf of the user.

@aivong-openhands can click here to continue refining the PR


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-5c04440

@github-actions

Copy link
Copy Markdown
Contributor

⚠️ This PR contains migrations. Please synchronize before merging to prevent conflicts.

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  migrations/versions
  174_add_procrastinate_schema.py 41-45, 49, 53-58
Project Total  

This report was generated by python-coverage-comment-action

@aivong-openhands
aivong-openhands force-pushed the task-queue/01-enrichment-guard branch from bf86e6e to dfa97bc Compare September 30, 2026 06:14
@aivong-openhands
aivong-openhands force-pushed the task-queue/02-procrastinate-schema branch from c591712 to c27fe11 Compare September 30, 2026 06:14
@aivong-openhands
aivong-openhands marked this pull request as ready for review September 30, 2026 15:09
…evision 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 <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands force-pushed the task-queue/02-procrastinate-schema branch from c27fe11 to f8db211 Compare September 30, 2026 15:18
@aivong-openhands
aivong-openhands changed the base branch from task-queue/01-enrichment-guard to main September 30, 2026 15:18
@aivong-openhands aivong-openhands changed the title feat(task-queue): add Procrastinate 3.10.0 and its vendored schema (revision 174) feat(task-queue): add Procrastinate and its database schema Sep 30, 2026
@aivong-openhands aivong-openhands changed the title feat(task-queue): add Procrastinate and its database schema feat(task-queue): PLTF-3689 add Procrastinate and its database schema Sep 30, 2026
Comment thread pyproject.toml Resolved

@hieptl hieptl left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thank you! 🙏

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review of the migration 174 tests

I broke migrations/versions/174_add_procrastinate_schema.py (and the vendored SQL) by hand in 11 ways and ran tests/unit/test_migration_174_procrastinate_schema.py against each one. Baseline: 6 passed on 76efdb4.

Caught: all four controls (reverting what the PR claims) and M4

Mutant Result
C1: upgrade() skips the vendored schema script ❌ caught
C2: downgrade() drops tables and functions but not the types ❌ caught
C3: TASK_QUEUE_DB_ROLE is ignored, so nothing is granted ❌ caught
C4: vendored SQL drifts from 3.10.0 (one index removed) ❌ caught
M4: DELETE left out of the table grant ❌ caught

The schema side is solid. _catalog() compares full sorted catalog snapshots with == against a database Procrastinate built itself, and the downgrade test asserts that every category is empty. So any change to the SQL, the drop list or the drop order fails a test. test_worker_role_runs_the_queue runs a real worker end to end, so it catches a missing privilege on any path a normal job uses (M4 dies because unregistering the worker needs DELETE).

Survivors

Mutant Result
M1: delete the ROLE_NAME_RE guard, so the role is interpolated unchecked ✅ 6 passed
M2: grant DML ON ALL TABLES IN SCHEMA public and USAGE ON ALL SEQUENCES IN SCHEMA public ✅ 6 passed
M3: GRANT ALL PRIVILEGES on the queue tables (adds TRUNCATE, TRIGGER, REFERENCES) ✅ 6 passed
M5: procrastinate_periodic_defers left out of the table grant ✅ 6 passed
M6: procrastinate_periodic_defers_id_seq left out of the sequence grant ✅ 6 passed
M7: .strip() removed from os.getenv('TASK_QUEUE_DB_ROLE', '') ✅ 6 passed

M1: the injection test passes even without the guard

'x; DROP TABLE org' is rejected, but not by ROLE_NAME_RE. With the guard deleted, the script becomes GRANT … TO x; DROP TABLE org; …. It fails because role x does not exist, the transaction rolls back, and the PostgresUnavailableError the test expects is raised anyway. So the test cannot tell the guard apart from an accident of the payload. It needs a payload that is valid SQL when interpolated, so that only the guard can make the migration fail. f'{role}, public' works: without the guard it quietly grants the queue tables to every role.

(I tried match='not a plain role name' first, but the ValueError text does not come through in the alembic subprocess output that run_alembic captures, so that assertion fails on the unmodified branch.)

M2 / M3 / M5 / M6: nothing pins what the worker role is actually granted

The PR says the role gets "read and write access to the queue tables but no permission to change the schema". The tests check the lower bound (a normal job runs) and a DDL denylist. Nothing checks the upper bound. Granting the worker DML on every table in public (org and every other app table), or TRUNCATE/TRIGGER on the queue tables, passes every test, even though limiting those privileges is the reason the variable exists. In the other direction, the end-to-end job never touches procrastinate_periodic_defers, so dropping its table or sequence grant passes too. Without the table grant it is worse than broken periodic tasks: the BEFORE DELETE trigger on procrastinate_jobs (procrastinate_unlink_periodic_defers_v1) updates that table, so deleting any job would fail with a permission error.

A snapshot of the role's grants closes all four:

@@ class TestWorkerRole:
+    def test_worker_role_privileges_are_exactly_queue_dml(self, worker_conninfo: str):
+        with psycopg.connect(worker_conninfo) as conn:
+            table_grants = set(
+                conn.execute(
+                    'SELECT table_name, privilege_type'
+                    '  FROM information_schema.role_table_grants'
+                    ' WHERE grantee = current_user'
+                ).fetchall()
+            )
+            sequences = {
+                name
+                for (name,) in conn.execute(
+                    'SELECT object_name FROM information_schema.usage_privileges'
+                    " WHERE grantee = current_user AND object_type = 'SEQUENCE'"
+                )
+            }
+        assert table_grants == {
+            (table, privilege)
+            for table in (
+                'procrastinate_workers',
+                'procrastinate_jobs',
+                'procrastinate_periodic_defers',
+                'procrastinate_events',
+            )
+            for privilege in ('SELECT', 'INSERT', 'UPDATE', 'DELETE')
+        }
+        assert sequences == {
+            'procrastinate_jobs_id_seq',
+            'procrastinate_periodic_defers_id_seq',
+            'procrastinate_events_id_seq',
+            'procrastinate_workers_id_seq',
+        }
+
     def test_rejects_role_name_that_is_not_an_identifier(
-        self, test_database: postgres_testdb.TestDatabase
+        self, test_database: postgres_testdb.TestDatabase, worker_role
     ):
+        role, _ = worker_role
         postgres_testdb.run_alembic(
             test_database.server, test_database.name, 'downgrade', '173'
         )
@@
-                extra_env={'TASK_QUEUE_DB_ROLE': 'x; DROP TABLE org'},
+                extra_env={'TASK_QUEUE_DB_ROLE': f'{role}, public'},
             )

Verified: with this change the file passes on the unmodified branch (7 passed), and M1, M2, M3, M5 and M6 are each killed. M4 is still killed too.

M7: low priority, no fix proposed

Without .strip(), a value with a leading or trailing space fails ROLE_NAME_RE and the migration stops with a ValueError. That fails closed and loudly, so I would not add a test just for it. (A trailing \n gets through either way, because $ matches before a final newline, and it is harmless in SQL.)

Not a test gap

  • TASK_QUEUE_DB_ROLE=public passes ROLE_NAME_RE (it is a plain identifier) and grants queue DML to every role in the database. You might want to reject it explicitly.

This comment was generated by an AI assistant on behalf of the user.

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 <openhands@all-hands.dev>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Follow-up on the mutation review. That review ran against 76efdb4. Since then, f5ba470 moved the worker-role grants out of revision 174 into migrations/env.py, renamed TASK_QUEUE_DB_ROLE to TASK_QUEUE_DB_USER, and switched from the ROLE_NAME_RE guard to quoting the role name. Here is how each finding looks at 66a6374:

Finding Status at 66a6374
C1–C4, M4 (schema side) Nothing to do. The catalog-snapshot and downgrade tests are unchanged, and they still cover these.
M1 (injection test passes without the guard) No longer applies. The guard and the 'x; DROP TABLE org' test are gone. The role name is now quoted, and a test covers quoting with a role name that has a space and a hyphen in it.
M2 / M3 (nothing checks the upper bound of the grants) Still open. No test compares the role's grants to an exact snapshot.
M5 / M6 (procrastinate_periodic_defers table and sequence) Less likely now, because grant_task_queue_role finds tables and sequences by the procrastinate_ prefix instead of listing them by hand. There is still no test for it. The snapshot test proposed for M2/M3 would cover it too.
M7 (.strip()) Low priority, as noted in the review.
public as the role name Still open, and quoting does not fix it. I checked on Postgres 16: GRANT SELECT ON procrastinate_jobs TO "public" shows up as a grant to PUBLIC, because Postgres matches the role name after unquoting. So TASK_QUEUE_DB_USER=public gives queue DML to every role.

I'm deferring every open item on purpose. All of them are in the TASK_QUEUE_DB_USER grant code, and @jlav's question in #587 (comment) asks whether that code should exist at all. That question is being handled separately. Changing the same code in parallel would mean duplicate or conflicting work.

  • If the grant is removed, all the open items go away with it.
  • If the grant stays, the follow-up is:
    • the exact-grants snapshot test from the review, updated for the current fixtures;
    • rejecting public (case-insensitive) in migrations/env.py, with a test.

This comment was generated by an AI agent (OpenHands) on behalf of the user.

openhands-agent and others added 2 commits September 30, 2026 20:53
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 <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands enabled auto-merge (squash) September 30, 2026 20:59
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 <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands merged commit e20ef06 into main Sep 30, 2026
19 checks passed
@aivong-openhands
aivong-openhands deleted the task-queue/02-procrastinate-schema branch September 30, 2026 21:18
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.68.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released: 1.68.0 Shipped in 1.68.0 type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants