Skip to content

fix(gitlab): PLTF-3689 claim webhook rows and support hook repair - #692

Merged
aivong-openhands merged 6 commits into
mainfrom
task-queue/gitlab-webhook-claim
Oct 19, 2026
Merged

aivong-openhands merged 6 commits into
mainfrom
task-queue/gitlab-webhook-claim

Conversation

@aivong-openhands

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

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Overlapping installer runs can select the same webhook rows and create duplicate hooks. Each run now claims its rows and checks ownership before creating a hook. Keeping credentials across attempts lets a retry adopt a hook created before a lost response.

Summary

  • Claim webhook rows and condition writes on the run ID; check ownership before creating a hook.
  • Preserve the UUID and secret across attempts.
  • Add python -m sync.repair_gitlab_hooks --project <id> or --group <id> to request repair through generation counters.

Issue Number

Refs #623.

How to Test

uv run pytest tests/unit/integrations/gitlab/test_gitlab_service.py tests/unit/sync/test_gitlab_webhook_claims.py

Video/Screenshots

N/A. No UI change.

Type

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

Notes

Builds on #681, which adds the claim columns and repair counters.

The repair command records a request for the installer to replace matching hooks. A process stalled after its final ownership check can still create a duplicate hook.


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-7c97f8b

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  integrations/gitlab
  gitlab_service.py 395-396, 434-436
  webhook_installation.py 313-314
  storage
  gitlab_webhook_store.py
  sync
  install_gitlab_webhooks.py 60, 106-107
  repair_gitlab_hooks.py 48-62, 66
Project Total  

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

Base automatically changed from task-queue/03-r1-schema to main October 7, 2026 22:18
…ns cannot double-install

Two runs of the GitLab webhook installer could read the same rows and each
create a hook on the same project or group (#623). The installer now claims
its rows: it locks them with SKIP LOCKED, stamps its run id, and makes every
later write conditional on still holding the claim. A run that stalls past
the 10-minute lease and loses its rows writes nothing and creates no hook.

Each row keeps one uuid and secret across attempts, written before the
create, so a hook whose create response was lost still authenticates and
the next run adopts it instead of adding a second.

sync/repair_gitlab_hooks.py records a reinstall request for a project or
group. The installer's next run deletes every hook with our URL on the
resource and creates one, then records the request it served, so a repair
requested during an install is not lost.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands force-pushed the task-queue/gitlab-webhook-claim branch from 1deb845 to 21ff3d9 Compare October 7, 2026 22:25
…ards (mutation review)

Add tests for SKIP LOCKED, claim order and limit, the admin-check delete
under a lost claim, a reinstall whose hook delete fails, repair touching
only the request counter, and the hook listing page size.
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review

Method: 23 hand-written mutants applied one at a time to the PR's source, running tests/unit/integrations/gitlab/test_gitlab_service.py and tests/unit/sync/test_gitlab_webhook_claims.py (baseline: 27 passed, real Postgres). Killing tests for the survivors were added in commit 3b7fee5; the suite is now 32 passed.

Controls (the PR's central claims)

Mutant Result
Drop skip_locked=True from the claim query ✅ survived (27 passed), now ❌ caught
Regenerate uuid + secret on every attempt ❌ caught
Ignore the result of the pre-create refresh_claim ❌ caught
Make the row delete in verify_webhook_conditions unconditional ❌ caught
Set reinstall_done_gen from the current reinstall_requested_gen column instead of the served generation ❌ caught
Installer also writes reinstall_requested_gen ❌ caught
request_reinstall also clears claim_run_id ❌ caught
Keep existence-check adoption during a reinstall ❌ caught
delete_webhooks_with_url stops after the first matching hook ❌ caught
update_claimed drops the claim_run_id condition ❌ caught

Nine of ten controls died on the original suite. What makes it work: GitLab is the only fake, the database is real, and the lost-claim tests take the claim over mid-run (on_admin_check / on_resource_check hooks) and then assert on the stored row and the fake's hook list, not on mock calls. test_repair_requested_during_a_reinstall_is_not_lost pins the generation counters as a tuple, which kills both generation mutants.

Survivors

Mutant Result on original suite
C1: drop skip_locked=True ✅ 27 passed
M3: reinstall ignores a failed / rate-limited hook delete and creates anyway ✅ 27 passed
M2: admin-check failure deletes the row unconditionally (lost claim) ✅ 27 passed
M1: request_reinstall also sets webhook_exists = false ✅ 27 passed
M4: claim query drops ORDER BY last_synced ✅ 27 passed
M5: claim query drops LIMIT ✅ 27 passed
M13: delete_webhooks_with_url drops per_page=100 ✅ 27 passed

C1: SKIP LOCKED

Without skip_locked, plain FOR UPDATE still gives disjoint claims, because Postgres rechecks the WHERE after the lock wait. So test_overlapping_runs_claim_different_rows passes either way. The observable difference is that a run blocks on rows another transaction holds instead of moving past them. Killing test, added in 3b7fee5:

async def test_a_row_locked_by_another_run_is_skipped_not_waited_on(
    store, add_row, async_session_maker
):
    locked = await add_row('locked')
    free = await add_row('free')

    async with async_session_maker() as session, session.begin():
        await session.execute(
            select(GitlabWebhook).where(GitlabWebhook.id == locked).with_for_update()
        )
        claimed = await asyncio.wait_for(store.claim_rows(uuid4(), CLAIM_LEASE), 5)

    assert [row.id for row in claimed] == [free]

Verified: passes on the branch, fails with the mutant (the claim waits on the lock and wait_for times out).

M3: reinstall after a failed delete

If delete_webhooks_with_url returns RATE_LIMITED or INVALID part way, the mutant still creates a hook and records reinstall_done_gen. The resource ends with the old hooks plus a new one, and the repair request counts as served, so it is not retried. That is the duplicate-hook state the repair command exists to fix. FakeGitLab.delete_webhooks_with_url never returned a status, so no test reached the branch. The fake now has delete_status, and this test was added in 3b7fee5:

async def test_reinstall_stops_when_the_old_hooks_cannot_be_deleted(
    store, gitlab, add_row, get_row
):
    row_id = await add_row(webhook_exists=True, reinstall_requested_gen=1)
    old = gitlab.add_hook('project-1')
    gitlab.delete_status = WebhookStatus.RATE_LIMITED

    await run_job()

    assert gitlab.hooks['project-1'] == [old]
    assert (await get_row(row_id)).reinstall_done_gen == 0

Verified: passes on the branch, fails with the mutant.

M2: admin-check delete under a lost claim

verify_webhook_conditions deletes the row in two places. The lost-claim test covered only the resource-missing one, so the admin-check delete could go unconditional and a stalled run could delete a row that a newer run holds. FakeGitLab now has is_admin, and test_run_that_lost_its_claim_does_not_delete_the_row is parametrized over failed_check in ['resource', 'admin'] (3b7fee5). Verified: [admin] passes on the branch and fails with the mutant.

M1: repair touches only the request counter

The repair tests start from rows where webhook_exists is already false, or where the reinstall sets it back to true. A repair that also cleared webhook_exists, credentials or the claim passed. Added in 3b7fee5:

async def test_repair_request_changes_only_the_request_counter(store, add_row, get_row):
    row_id = await add_row(
        webhook_exists=True, webhook_uuid='uuid-1', webhook_secret='secret-1'
    )
    before = await get_row(row_id)

    assert await request_repair(GitLabResourceType.PROJECT, 'project-1')

    after = await get_row(row_id)
    assert after.reinstall_requested_gen == before.reinstall_requested_gen + 1
    unchanged = ('webhook_exists', 'webhook_uuid', 'webhook_secret', 'claim_run_id')
    assert {f: getattr(after, f) for f in unchanged} == {
        f: getattr(before, f) for f in unchanged
    }
    assert after.reinstall_done_gen == before.reinstall_done_gen

Verified: passes on the branch, fails with the mutant.

M4 / M5: claim order and limit

Without ORDER BY last_synced, a block of rows that fail every run could starve the rest of the table. Without LIMIT, one run claims every row and cannot finish them inside the job deadline. No test claimed fewer rows than were eligible. One test kills both, added in 3b7fee5. It inserts rows newest-first, so physical order differs from sync order:

async def test_rows_are_claimed_least_recently_synced_first(store, add_row):
    newest = await add_row('newest', last_synced=datetime(2026, 3, 1))
    oldest = await add_row('oldest', last_synced=datetime(2026, 1, 1))
    middle = await add_row('middle', last_synced=datetime(2026, 2, 1))

    claimed = await store.claim_rows(uuid4(), CLAIM_LEASE, limit=2)

    assert [row.id for row in claimed] == [oldest, middle]
    assert newest not in {row.id for row in claimed}

Verified: passes on the branch, fails with each mutant.

M13: hook listing page size

GitLab returns 20 hooks per page by default. Without per_page=100, a resource with more than 20 hooks keeps the hooks past the first page after a reinstall. The mocked _make_request ignored params. test_deletes_every_hook_with_the_url_and_no_other now also asserts mock_request.call_args_list[0].kwargs['params'] == {'per_page': 100} (3b7fee5). Verified both ways.

Equivalent mutants (no test added)

  • M6: release_claim drops last_synced=CURRENT_TIMESTAMP. The column has onupdate=text('CURRENT_TIMESTAMP'), and that fires on the Core update() too. A probe test showing that last_synced advances still passed with the mutant. This looks like an equivalent mutant: the explicit assignment is redundant with onupdate.
  • M8: a rejected adoption write in verify_webhook_conditions does not raise. The run then reaches the claim-conditional credentials write or refresh_claim, which both stop it before any GitLab create. This looks like an equivalent mutant, because a later guard covers it. Either a case is missing or the raise is defense in depth only.
  • M10: the final write omits webhook_url / scopes. No code in the repo reads these columns from a row, so no behaviour changes. This looks like an equivalent mutant unless something outside the repo reads them.

Not a test gap

  • delete_webhooks_with_url reads one page of up to 100 hooks and does not paginate. A resource with more than 100 matching hooks keeps the extra hooks after a reinstall.
  • No hangs.

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

…reinstall

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

Copy link
Copy Markdown
Contributor Author

Addressed the one open item from the mutation review in 1164483: delete_webhooks_with_url now follows the Link: rel="next" header and collects every matching hook id before deleting, so a resource with more than 100 hooks no longer keeps stale hooks after a reinstall. Added test_deletes_matching_hooks_on_every_page.

The equivalent mutants (M6, M8, M10) are left as is: M6's explicit last_synced and M8's raise are harmless defense in depth, and M10's webhook_url/scopes columns were already written before this PR.

Ran TestDeleteWebhooksWithUrl locally (3 passed, ruff clean). The Postgres-backed claim tests were not run here because there is no Docker in this environment, so CI needs to confirm them.

This comment was created 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.

Taste: acceptable. The claim/ownership design is sound. One blocking CI failure remains.

Material finding

Lint python fails on the current head (116448393, CI run 37706845123): mypy reports integrations/gitlab/gitlab_service.py:414: Need type annotation for "hook_ids" [var-annotated]. It was introduced by the pagination commit. See the inline comment for the fix.

Checked and found sound

  • claim_rows uses FOR UPDATE SKIP LOCKED with ORDER BY last_synced and a LIMIT. Claim columns are set in the same transaction as the select.
  • All writes, deletes and the release go through claim_run_id-conditional statements, so a run that lost its claim changes nothing.
  • The uuid and secret are written before any create call and reused, so a retry can adopt a hook whose create response was lost.
  • The installer never writes reinstall_requested_gen. It records the generation it served, so a repair requested mid-run is not lost. Failed deletes or creates leave reinstall_done_gen behind, so the next run retries.
  • delete_webhooks_with_url lists every page before deleting. This is compatible with the Link header returned by _make_request.
  • No remaining callers of the removed filter_rows, update_last_synced or VerifyWebhookStatus helper methods. Other callers of verify_webhook_conditions and install_webhook_on_resource are unaffected because the new parameters have defaults.
  • Tests use a real database and a fake GitLab, take over claims mid-run, and assert on stored state.

Merge gate

Hold the merge until Lint python is green and Python Tests (which runs the Postgres claim tests the author could not run locally) passes on the head commit. Python Tests was still running when this review was written.

[RISK ASSESSMENT]
⚠️ Risk Assessment: 🟡 MEDIUM. Concurrency and claim logic in a scheduled job that creates external GitLab hooks and handles webhook secrets, plus a new operator-run repair command. The blast radius is limited to the GitLab webhook installer. Reviewers should focus on lease and claim semantics. No human gate is required once CI is green.

Verdict: Changes needed: fix the mypy error. Posted as a COMMENT because GitHub does not allow requesting changes on one's own PR; otherwise I would approve.

Key insight: putting the ownership check and stored credentials at the write boundary makes retries safe, which is a better fix than trying to prevent overlapping runs.

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.

Comment thread integrations/gitlab/gitlab_service.py Resolved
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Local validation — overlapping installer runs, lost creates and repair

The bugs: without this PR, the GitLab webhook installer reads rows without claiming them, so two overlapping runs can each install a hook on the same project or group (#623). Each run also generates fresh credentials and writes them only after GitLab answers the create, so when that answer is lost, the next run adopts a hook whose credentials the row never recorded, and GitLab's deliveries to it are rejected.

How the test triggers them: the real sync.install_gitlab_webhooks and sync.repair_gitlab_hooks run against a local Postgres 16 database at alembic 177 and a fake GitLab API that keeps hooks per resource and can delay a create or drop its response. Only the API base URL and the user's GitLab token (which production gets from Keycloak) are replaced. A hook "authenticates" when its token and X-OpenHands-Webhook-ID equal the row's webhook_secret and webhook_uuid. "Before" uses this PR's merge base (dbdc6e5) for the installer, webhook_installation.py, the store and the GitLab service; "after" is this PR at 549025b.

Outcome Before After
Two installer runs start together on 8 projects that need a hook: projects left with two hooks 8 of 8 (one hook of each pair authenticates) 0; each project has one hook, which authenticates
GitLab creates the hook but its response is lost; the next run adopts it: adopted hook authenticates No Yes; no second hook is created
repair_gitlab_hooks --project on a project with the row's hook and a same-URL hook with other credentials No repair command Next run deletes both and creates one, which authenticates; reinstall_requested_gen/reinstall_done_gen 1/1
Repair requested while an installer run waits on its create No repair command The create completes and that run leaves the generations at 1/0; the next run deletes that hook and creates one, which authenticates; 1/1

uv run --group test pytest tests/unit/sync/test_gitlab_webhook_claims.py tests/unit/integrations/gitlab/test_gitlab_service.py: 33 passed.

@aivong-openhands
aivong-openhands enabled auto-merge (squash) October 19, 2026 14:24
@aivong-openhands
aivong-openhands merged commit 6c1b4a7 into main Oct 19, 2026
16 checks passed
@aivong-openhands
aivong-openhands deleted the task-queue/gitlab-webhook-claim branch October 19, 2026 14:46
@openhands-release-bot openhands-release-bot Bot added the released: 1.73.0 Shipped in 1.73.0 label Oct 19, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.73.0.

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

Labels

released: 1.73.0 Shipped in 1.73.0 type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants