Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions migrations/versions/177_add_scheduled_job_claim_columns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Add per-run claim columns to maintenance_tasks and gitlab_webhook (PLTF-3689).

The budget/maintenance runner and the GitLab webhook installer claim their rows
so two runs of a job cannot work on the same row (#552, #623). A claim is the
run's id and when it was taken; every later write is conditional on the run
still holding it. ``gitlab_webhook`` also gets a reinstall request counter and
the generation the installer last served: a row needs a reinstall while the
request is ahead. Nothing reads the columns until the claim code ships; the new
counters start equal, so no row needs a reinstall.

Revision ID: 177
Revises: 176
Create Date: 2026-10-07 00:00:00.000000
"""

from typing import Sequence

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects.postgresql import UUID

revision: str = '177'
down_revision: str | None = '176'
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

CLAIMED_TABLES = ('maintenance_tasks', 'gitlab_webhook')
GENERATIONS = ('reinstall_requested_gen', 'reinstall_done_gen')


def upgrade() -> None:
for table in CLAIMED_TABLES:
op.add_column(table, sa.Column('claim_run_id', UUID(as_uuid=True)))
op.add_column(table, sa.Column('claimed_at', sa.DateTime(timezone=True)))
for column in GENERATIONS:
op.add_column(
'gitlab_webhook',
sa.Column(column, sa.Integer(), nullable=False, server_default='0'),
)


def downgrade() -> None:
for column in GENERATIONS:
op.drop_column('gitlab_webhook', column)
for table in CLAIMED_TABLES:
op.drop_column(table, 'claimed_at')
op.drop_column(table, 'claim_run_id')
16 changes: 16 additions & 0 deletions storage/gitlab_webhook.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime
from enum import IntEnum
from typing import Any
from uuid import UUID

from sqlalchemy import (
ARRAY,
Expand All @@ -9,6 +10,7 @@
Text,
text,
)
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column

from storage.base import Base
Expand Down Expand Up @@ -43,6 +45,20 @@ class GitlabWebhook(Base):
onupdate=text('CURRENT_TIMESTAMP'),
nullable=True,
)
claim_run_id: Mapped[UUID | None] = mapped_column(
PG_UUID(as_uuid=True), nullable=True
)
claimed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
# A row needs a reinstall while the request is ahead of the generation the
# installer last served.
reinstall_requested_gen: Mapped[int] = mapped_column(
default=0, server_default='0', nullable=False
)
reinstall_done_gen: Mapped[int] = mapped_column(
default=0, server_default='0', nullable=False
)

def __repr__(self) -> str:
return (
Expand Down
8 changes: 8 additions & 0 deletions storage/maintenance_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
from datetime import datetime
from enum import Enum
from typing import Any
from uuid import UUID

from pydantic import BaseModel, ConfigDict
from sqlalchemy import DateTime, String, Text, text
from sqlalchemy import Enum as SQLEnum
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column

from openhands.app_server.utils.import_utils import get_impl
Expand Down Expand Up @@ -70,6 +72,12 @@ class MaintenanceTask(Base):
processor_json: Mapped[str] = mapped_column(Text, nullable=False)
delay: Mapped[int] = mapped_column(default=0, server_default='0', nullable=False)
started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
claim_run_id: Mapped[UUID | None] = mapped_column(
PG_UUID(as_uuid=True), nullable=True
)
claimed_at: Mapped[datetime | None] = mapped_column(
DateTime(timezone=True), nullable=True
)
info: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime, server_default=text('CURRENT_TIMESTAMP'), nullable=False
Expand Down
109 changes: 109 additions & 0 deletions tests/unit/test_migration_177_scheduled_job_claim_columns.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""Revision 177 adds the claim columns the scheduled jobs' claims use."""

import uuid

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

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

NEW_COLUMNS = {
('maintenance_tasks', 'claim_run_id', 'uuid', 'YES', None),
('maintenance_tasks', 'claimed_at', 'timestamp with time zone', 'YES', None),
('gitlab_webhook', 'claim_run_id', 'uuid', 'YES', None),
('gitlab_webhook', 'claimed_at', 'timestamp with time zone', 'YES', None),
('gitlab_webhook', 'reinstall_requested_gen', 'integer', 'NO', '0'),
('gitlab_webhook', 'reinstall_done_gen', 'integer', 'NO', '0'),
}


def _new_columns(engine: Engine) -> set[tuple]:
with engine.connect() as conn:
rows = conn.execute(
text(
'SELECT table_name, column_name, data_type, is_nullable, '
'column_default FROM information_schema.columns '
"WHERE table_schema = 'public' AND table_name IN "
"('maintenance_tasks', 'gitlab_webhook')"
)
)
columns = {tuple(row) for row in rows}
names = {column[:2] for column in NEW_COLUMNS}
return {column for column in columns if column[:2] in names}


def test_upgrade_adds_the_claim_columns(engine: Engine):
assert _new_columns(engine) == NEW_COLUMNS


def test_existing_webhook_rows_need_no_reinstall(
engine: Engine, test_database: postgres_testdb.TestDatabase
):
postgres_testdb.run_alembic(
test_database.server, test_database.name, 'downgrade', '176'
)
with engine.begin() as conn:
conn.execute(
text(
'INSERT INTO gitlab_webhook (project_id, user_id, webhook_exists) '
"VALUES (:project, 'user-1', true)"
),
{'project': uuid.uuid4().hex},
)

postgres_testdb.run_alembic(
test_database.server, test_database.name, 'upgrade', 'head'
)

with engine.connect() as conn:
row = conn.execute(
text(
'SELECT claim_run_id, claimed_at, reinstall_requested_gen, '
'reinstall_done_gen FROM gitlab_webhook'
)
).one()
assert tuple(row) == (None, None, 0, 0)


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)


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)


def test_downgrade_removes_the_columns_and_upgrade_restores_them(
engine: Engine, test_database: postgres_testdb.TestDatabase
):
postgres_testdb.run_alembic(
test_database.server, test_database.name, 'downgrade', '176'
)
assert _new_columns(engine) == set()

postgres_testdb.run_alembic(
test_database.server, test_database.name, 'upgrade', 'head'
)
assert _new_columns(engine) == NEW_COLUMNS
Loading