Skip to content

feat(task-queue): PLTF-3689 add per-run claim columns for scheduled jobs - #681

Merged
aivong-openhands merged 6 commits into
mainfrom
task-queue/03-r1-schema
Oct 7, 2026
Merged

aivong-openhands merged 6 commits into
mainfrom
task-queue/03-r1-schema

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Two runs of the same scheduled job can take the same row today. The maintenance task runner picks the oldest pending task without a lock (#552), and the GitLab webhook installer reads up to 100 rows without a lock, so two runs can each install a hook on the same project or group (#623).

This adds the columns for a per-run claim: a run locks its rows, stamps them with its claim_run_id and claimed_at, and makes every later write conditional on still holding that id. gitlab_webhook also gets reinstall_requested_gen and reinstall_done_gen, so a repair command can request a hook reinstall that an install already in progress cannot clear. Nothing reads the columns yet; the claim columns are nullable and both counters default to 0, so no existing row needs a reinstall.

Summary

  • Migration 177 adds claim_run_id and claimed_at to maintenance_tasks and gitlab_webhook, and the two reinstall counters to gitlab_webhook.
  • The MaintenanceTask and GitlabWebhook models gain the matching fields.

Issue Number

Prepares the fixes for #552 and #623.

How to Test

tests/unit/test_migration_177_scheduled_job_claim_columns.py upgrades and downgrades between 176 and 177, checks each column's type and default against the models, and checks that existing and new webhook rows need no reinstall.

Video/Screenshots

N/A. No UI change.

Type

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

Notes

Adds migration 177. #691 and #692 build on this branch.


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


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-18fb00a

@github-actions github-actions Bot added the type: feat A new feature label Oct 6, 2026
…til the R1 bootstrap

Revision 177 adds the tables, columns and triggers the CronJob to
Procrastinate migration needs. Both permits start closed and the bootstrap
starts pending, so nothing reads or writes them yet and the seven CronJobs
run as today.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands force-pushed the task-queue/03-r1-schema branch from b76d52b to bec16c5 Compare October 6, 2026 19:52
@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  migrations/versions
  177_add_scheduled_job_claim_columns.py 32-36, 43-47
  storage
  gitlab_webhook.py 64
  maintenance_task.py
Project Total  

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

@aivong-openhands aivong-openhands changed the title feat(task-queue): PLTF-3689 add the scheduled-job schema, inactive until the R1 bootstrap feat(task-queue): PLTF-3689 add the scheduled-job schema Oct 6, 2026
Replace the rev 33 scheduled-job schema with the columns the per-run claims
need (plan rev 45, sections 3.1 and 3.2): claim_run_id and claimed_at on
maintenance_tasks and gitlab_webhook, and reinstall_requested_gen and
reinstall_done_gen on gitlab_webhook. Nothing reads them until the claim
code ships.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands aivong-openhands changed the title feat(task-queue): PLTF-3689 add the scheduled-job schema feat(task-queue): PLTF-3689 add per-run claim columns for scheduled jobs Oct 7, 2026
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review of the tests in this PR

Method: I hand-wrote 10 mutants against the diff at 24fdf30 and ran each one against a pristine worktree on Postgres 16. Migration mutants ran against tests/unit/test_migration_177_scheduled_job_claim_columns.py, where the baseline is 3 passed. Model mutants also ran against the existing test modules that use GitlabWebhook and MaintenanceTask (the gitlab webhook store, install and route tests, plus the maintenance runner and status tests), where the baseline is 74 passed.

Controls (they should fail, and they did)

Mutant Result
C1: claim columns only on gitlab_webhook, not on maintenance_tasks ❌ caught
C2: generation counters default to 1 instead of 0 ❌ caught
M1: claimed_at migrated as timestamp without time zone ❌ caught
M2: migration backfills existing rows with reinstall_requested_gen = 1 ❌ caught
M3: downgrade leaves maintenance_tasks.claimed_at behind ❌ caught
M4: GitlabWebhook.claim_run_id mapped as Text instead of UUID ❌ caught by the existing async store tests (uuid vs character varying on insert)

The migration side is pinned well. test_upgrade_adds_the_claim_columns compares the whole (table, column, type, nullable, default) set for equality, so a wrong type, a wrong default or a missing column all fail it. The downgrade test asserts the columns are actually gone before it upgrades again, so it fails if a drop is skipped. Planting a row at 176 and upgrading is what kills M2, which the empty-template check alone would miss.

Survivors

Mutant Result
M6: GitlabWebhook.reinstall_requested_gen ORM default=1 (server default stays 0) ✅ 74 passed
M5: MaintenanceTask.claimed_at mapped as naive DateTime ✅ 74 passed
M7: reinstall_done_gen removed from the GitlabWebhook model ✅ 74 passed
M8: claim_run_id and claimed_at removed from the MaintenanceTask model ✅ 74 passed

All four are in the ORM models. The new tests only use raw SQL and information_schema, so nothing checks that storage/gitlab_webhook.py and storage/maintenance_task.py match what migration 177 creates.

M6: rows added through the ORM would start out needing a reinstall

The ORM default= takes precedence over the server default on every session.add(GitlabWebhook(...)). If the two disagree, rows written by the app get requested=1, done=0, while the migration test, which writes raw SQL, still sees 0, 0. Once the installer reads these counters, every newly added webhook would be reinstalled. test_existing_webhook_rows_need_no_reinstall covers the same invariant, but only for rows that existed before the upgrade.

def test_a_webhook_row_added_through_the_model_needs_no_reinstall(
    session_maker: sessionmaker,
):
    with session_maker() as session:
        session.add(
            GitlabWebhook(project_id='p-1', user_id='user-1', webhook_exists=True)
        )
        session.commit()
        row = session.scalars(select(GitlabWebhook)).one()
        assert (row.reinstall_requested_gen, row.reinstall_done_gen) == (0, 0)

M5, M7 and M8: model and migration can drift apart

Nothing reads these attributes yet, so today the only cost would be that the model no longer describes the column. The claim code that follows this PR will be written against the model, though. If claimed_at is declared naive on a timestamptz column, or an attribute is missing, the first failure will show up in that later PR and not in this one. A single test that compares each new column's model type with the migrated type kills all three. A missing attribute fails with a KeyError on table.c[...].

def test_models_map_the_migrated_column_types(engine: Engine):
    dialect = postgresql.dialect()
    inspector = inspect(engine)
    for model in (MaintenanceTask, GitlabWebhook):
        table = model.__table__
        migrated = {c['name']: c for c in inspector.get_columns(table.name)}
        for table_name, column_name, *_ in NEW_COLUMNS:
            if table_name != table.name:
                continue
            model_type = table.c[column_name].type.compile(dialect)
            migrated_type = migrated[column_name]['type'].compile(dialect)
            assert model_type == migrated_type, (table_name, column_name)

Both tests need these imports:

from sqlalchemy import inspect, select, text
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import sessionmaker

from storage.gitlab_webhook import GitlabWebhook
from storage.maintenance_task import MaintenanceTask

Verified: I appended both tests to the new test module. On the unmodified PR branch the module passes (5 passed) and ruff check and ruff format --check are clean. With each mutant applied, the module fails: M4, M5, M6, M7 and M8 are all caught. The module still runs in about 22 s.

Not a test gap

  • The PR description no longer matches the diff. It describes 13 new tables, three triggers, webhook_secret_v2, the resend_synced_users columns and a test file named test_migration_177_scheduled_job_schema.py. The head commit cuts the migration down to the claim columns plus the two reinstall_*_gen counters, and the description doesn't mention the counters. The "How to Test" section, including the 227-test Postgres 15 run, describes the earlier version.

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

Add a test that a webhook added through the ORM needs no reinstall, and a
test that the model types of the new columns match the migrated types.

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Contributor Author

Thanks for the mutation review. I addressed it in 3338bac.

  • I added both suggested tests to tests/unit/test_migration_177_scheduled_job_claim_columns.py: test_a_webhook_row_added_through_the_model_needs_no_reinstall and test_models_map_the_migrated_column_types.
  • The module passes against local Postgres (5 passed), and pre-commit (ruff, ruff format, mypy) is clean.
  • I re-applied the four mutants that survived before. Each one now fails the module:
    • M6: ORM default=1 makes 1 test fail.
    • M5: naive claimed_at makes 1 test fail.
    • M7: removing reinstall_done_gen makes 2 tests fail.
    • M8: removing the MaintenanceTask claim columns makes 1 test fail.
  • On the PR description: the current description already matches the reduced migration. It covers the reinstall_*_gen counters, names the right test file, and no longer mentions the 13 tables or the triggers. I also updated "How to Test" to mention the two new model checks.

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

@aivong-openhands aivong-openhands left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Overall: good. No material issues found at 3338bacf. All CI checks pass.

  • Migration: 177 follows 176, the latest on main, and no other open PR adds a migration with that number. The new columns are all nullable or have a constant default, so on PostgreSQL 11+ the upgrade only updates the catalog and doesn't rewrite the tables. The downgrade drops the columns in reverse order.
  • Model matches migration: the types match, and the counters have the same Python-side and server default (0). GitlabWebhookStore.store_webhooks inserts rows from webhook.__dict__, and rows inserted that way still start at 0/0, so new webhooks aren't flagged for a reinstall.
  • No behavior change: no current code reads or writes the new columns.
  • Tests: they check every column's type and default, existing rows and rows added through the model, that the model matches the migrated types, and that downgrade then upgrade works. Locally against PostgreSQL: 88 passed.

Non-blocking: the rules for using these columns are only written in comments: every write must check the run still holds its claim, and the installer never changes reinstall_requested_gen. The follow-up PRs that read these columns need tests where two runs compete for the same row.

[RISK ASSESSMENT]
[Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM
It changes the production schema, but the change is additive, reversible, and nothing reads the columns yet. Worth checking upgrade and downgrade on a staging copy.

Verdict: worth merging once the PR is out of draft. No changes requested. Posted as a comment because GitHub doesn't let the PR author approve their own PR.

Improve this review? If feedback seems incorrect or irrelevant, update the repository's .agents/skills/custom-codereview-guide.md (with the /codereview trigger), then re-request review. The reviewer reads the guide from the PR head.

Resolve with AI? Install the iterate skill and run /iterate.

Was this review helpful? React with 👍 or 👎.


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

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Replicated (Embedded Cluster) validation — migration 177

Setup: fresh Embedded Cluster install of a release running enterprise-server:sha-3338bac (this PR's head), with external Postgres and GitLab login.

Check Result
Migration alembic_version is 177.
gitlab_webhook columns claim_run_id uuid, nullable; claimed_at timestamptz, nullable; reinstall_requested_gen integer, not null, default 0; reinstall_done_gen integer, not null, default 0.
maintenance_tasks columns claim_run_id uuid, nullable; claimed_at timestamptz, nullable.
Rows created by the app After a GitLab login, 4 gitlab_webhook rows, all with reinstall_requested_gen = reinstall_done_gen = 0 and claim_run_id null.
Scheduled jobs install-gitlab-webhooks completes on every run against the migrated table, with no errors in its logs. budget-maintenance completes. No failed Jobs.
End to end Login, new conversation, sandbox started, agent replied. All pods Running/Completed.

On a fresh install the migration creates the columns as specified, rows added through the app start with no reinstall pending, and the jobs that use these tables keep running.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Local validation — migration 177 with existing rows and real jobs

Setup: this PR at 18fb00a, against a local Postgres 16 database. Before the upgrade, the database was migrated to 176 and seeded with 3 gitlab_webhook rows (2 projects, 1 group) and 2 maintenance_tasks rows (COMPLETED, PENDING).

Step Result
alembic upgrade 177 Adds gitlab_webhook.claim_run_id (uuid, nullable), claimed_at (timestamptz, nullable), reinstall_requested_gen and reinstall_done_gen (integer, not null, default 0), and maintenance_tasks.claim_run_id, claimed_at. All 3 existing webhook rows have reinstall_requested_gen = reinstall_done_gen = 0; all claim columns are null.
alembic downgrade 176 The six columns are removed; all 5 rows remain.
alembic upgrade head Same state as the first upgrade.
python -m run_maintenance_tasks at 177 Exit 0.
python -m sync.install_gitlab_webhooks at 177 Exit 0; processes the row with webhook_exists = false.
Same two jobs against a 176 database Exit 1 with UndefinedColumn on maintenance_tasks.claim_run_id and gitlab_webhook.claim_run_id.

uv run --group test pytest tests/unit/test_migration_177_scheduled_job_claim_columns.py: 5 passed.

@aivong-openhands
aivong-openhands marked this pull request as ready for review October 7, 2026 22:03
@aivong-openhands
aivong-openhands merged commit bebd747 into main Oct 7, 2026
24 of 25 checks passed
@aivong-openhands
aivong-openhands deleted the task-queue/03-r1-schema branch October 7, 2026 22:18
hieptl added a commit that referenced this pull request Oct 8, 2026
Main added migrations 176 (user.password_hash, #544) and 177 (scheduled
job claim columns, #681), the same revision ids as this branch's
instance_settings migrations. Alembic would see duplicate revisions and
two heads, so the branch's four migrations move after main's:

- 176_create_instance_settings -> 178 (revises 177)
- 177_add_setup_state_to_instance_settings -> 179
- 178_add_user_is_disabled -> 180
- 179_add_org_status -> 181

Text conflicts kept both sides: the Super Admin feature flag next to
main's integrated-IDP and OAuth v2 login flags, both router imports,
both authorization imports, and user.is_disabled next to
user.password_hash.
@openhands-release-bot openhands-release-bot Bot added the released: 1.70.0 Shipped in 1.70.0 label Oct 8, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.70.0.

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants