Skip to content

install-gitlab-webhooks isn't safe to run concurrently #623

Open

Description

@aivong-openhands

Summary

install-gitlab-webhooks selects its work rows without claiming them. Two runs at the same time process the same rows and can install the same webhook twice. Only the CronJob's concurrencyPolicy: Forbid prevents that today, so the job isn't safe to run concurrently (for example, a manual run during a scheduled one, more than one replica, or a stalled run whose work is reclaimed while its process is still alive).

Split out of #554, which now covers only enrich-user-interaction (fixed by #586).

Details

install-gitlab-webhooks runs every minute when enabled:

  • GitlabWebhookStore.filter_rows selects up to 100 rows with webhook_exists = false, ordered by last_synced, with no row lock.
  • Two concurrent runs get the same rows and can both call create_new_webhook for the same resource.
  • The existence check in check_if_webhook_already_exists_on_resource runs before the create, so it doesn't close the race between check and create. It matches on URL only, so it can't tell our hooks apart.
  • GitLab doesn't return a hook's secret token, so a hook with the right URL isn't necessarily one that authenticates.

Impact

  • With concurrencyPolicy: Forbid: none, as long as the job only ever runs from its CronJob.
  • Whenever two runs overlap: duplicate GitLab webhooks can be installed on the same project or group. Only the hook whose uuid and secret match the row authenticates; the others get 403 on every delivery and stay until someone removes them.
  • When the authenticating hook changes (for example, while a duplicate is cleaned up): GitLab queues deliveries per hook and sends them later, so one event can reach us through two hooks that each authenticate at the moment they're sent. The handler's current dedupe is a 60-second Redis key on object_attributes.id, which doesn't cover that. It also collides across distinct events on the same issue.

Proposed fix

A claim alone doesn't prevent every duplicate. A run whose claim has expired and been taken over can still call GitLab, because the create happens outside our database. The fix has five parts (plan rev 19, section 4.6):

  • Claim rows per run. Add claim_run_id and claimed_at to the GitLab webhook rows. Claim with SELECT ... FOR UPDATE SKIP LOCKED, stamping the run's ID. Every later write is conditional on WHERE claim_run_id = :run_id, so a run that lost its claim writes nothing (counted as stale_write_rejected). A claim older than the lease may be reclaimed.
  • Give every hook an identity. Before each create, record an intent (gitlab_hook_intent: uuid, row, run, state open) in a committed transaction. Then create the hook with URL GITLAB_WEBHOOK_URL?oh_hook=<uuid>. The handler is unchanged: it still authenticates by the X-OpenHands-Webhook-ID header and token. Every change to a row's uuid and secret is a conditional write that names the uuid it replaces and an open intent. A run never reuses an intent, so at most one hook ever carries the row's current identity.
  • Repair by a rule that stays correct when it runs late. A visit lists the resource's hooks, then reads the intents in a transaction started after the listing. It deletes only hooks whose intent can never become current: abandoned, replaced, or missing. An open intent within its lease is never abandoned, so a live install keeps its hook whatever the visit read earlier. Repair runs as a fast path over recently completed rows plus a daily full sweep.
  • Convert legacy hooks rather than adopting them. A hook with the plain URL predates the identity scheme, and its credentials are unknown. Under a row lock, the visit edits the legacy hook with the lowest id to a fresh identity and secret. It deletes the other legacy hooks, then commits the row only if its uuid is unchanged. If the row has no credentials, its legacy hooks can't authenticate, so the visit deletes them and lets the install recreate one.
  • Deduplicate deliveries durably. Replace the Redis key with a gitlab_delivery table keyed on a sha256 of the raw request body. INSERT ... ON CONFLICT DO NOTHING runs before any processing, and entries are kept for 7 days. X-Gitlab-Event-UUID and Idempotency-Key can't be the key, because GitLab doesn't keep them identical across hooks.

Ownership is already unique: UNIQUE (project_id) and UNIQUE (group_id) (migration 027), plus a per-environment GITLAB_WEBHOOK_URL, mean each resource has one owning row.

Acceptance criteria

  • Two overlapping runs claim different rows, and a resource ends up with exactly one hook.
  • A run whose claim was taken over writes no row state; its hook gets 403 and is deleted at the next visit.
  • A visit reads a row, then a host claims it, creates a hook and commits, then the visit lists and deletes: the new hook survives.
  • A visit stalls between deciding and deleting while a host commits a new hook: the new hook survives.
  • A create that times out after GitLab made the hook is retried under a new intent, and the first hook is deleted.
  • One legacy hook with the right URL and mismatched credentials is converted, and a test delivery through it is accepted.
  • Two stale conversions of one row: one commit succeeds, and the other's hook gets 403 and is deleted.
  • Before any cleanup, the same event delivered through two authenticating hooks (in both orders and concurrently) starts one conversation.
  • Verified on GitLab.com and the oldest supported self-managed version:
    • the hooks API returns the ?oh_hook= URL unchanged;
    • PUT .../hooks/:id sets the URL, token and custom headers for project and group hooks;
    • two hooks on one resource receive byte-identical bodies for one event.

Guarantees and accepted limits

  • No GitLab event is processed twice, however many hooks authenticate.
  • The deletion rule never deletes a hook that carries, or can come to carry, the current identity.
  • A legacy conversion that loses its row lock can delete a hook that another conversion just converted. This needs the set of legacy hooks to change in between. The next visit reinstalls, and deliveries in between are lost.
  • During a conversion, deliveries are refused with 403 for as long as the edit and deletes take, once per row.

Dependencies


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

Activity

  1. added
    enhancement
    on Oct 2, 2026
  2. aivong-openhands commented on Oct 19, 2026

    @aivong-openhands
    ContributorAuthor

    Status update

    Partly fixed. #681 and #692 claim rows per run and keep a row's credentials across attempts. #874 can now run the job on the procrastinate worker (off by default). Hook identity, automatic repair, legacy conversion and durable delivery dedupe aren't built yet.

    Done:

    • feat(task-queue): PLTF-3689 add per-run claim columns for scheduled jobs #681 (migration 177) adds claim_run_id, claimed_at, reinstall_requested_gen and reinstall_done_gen to gitlab_webhook.
    • fix(gitlab): PLTF-3689 claim webhook rows and support hook repair #692:
      • GitlabWebhookStore.claim_rows claims up to 100 rows with FOR UPDATE SKIP LOCKED and stamps each with the run's ID. The lease is 10 minutes.
      • Every later write is conditional on claim_run_id. A run that lost its claim writes nothing and logs gitlab_webhook.stale_write_rejected.
      • install_claimed_webhook writes the row's uuid and secret before the create and keeps them across attempts. If a create succeeded but its response was lost, the hook still authenticates and the next run adopts it. This replaces the "new intent, delete the first hook" approach in the proposed fix.
      • python -m sync.repair_gitlab_hooks --project|--group <id> asks the installer to delete every hook with our URL on the resource and create one. It's manual only; nothing runs it automatically.
    • feat(worker): PLTF-3689 run the CronJob jobs as periodic worker tasks #874 runs the job as the worker's install_gitlab_webhooks periodic task (* * * * *). Runs don't overlap because of a procrastinate lock and queueing_lock. The task is off unless OH_WORKER_SCHEDULED_JOBS_INSTALL_GITLAB_WEBHOOKS=true, so Kubernetes installs keep the CronJob and concurrencyPolicy: Forbid.

    Still open:

    1. Hook identity: there's no ?oh_hook=<uuid> URL and no gitlab_hook_intent table.
    2. Automatic repair: there's no fast path after installs and no daily sweep, only the manual command above.
    3. Legacy hook conversion: not built.
    4. Durable delivery dedupe: the handler still uses the 60-second Redis key. There's no gitlab_delivery table.
    5. The reinstall API route skips claims. POST /gitlab/reinstall-webhook calls reset_webhook_for_reinstallation_by_resource (sets webhook_exists=false, webhook_uuid=NULL). It then calls install_webhook_on_resource, which writes new credentials unconditionally. A scheduled run can claim the same row at the same time and install its own hook. The result is two hooks, and the one whose credentials were overwritten gets 403 on every delivery.
    6. A race remains after the last claim check. fix(gitlab): PLTF-3689 claim webhook rows and support hook repair #692's notes acknowledge this. A run that stalls between refresh_claim and the create, and whose claim is taken over, can still create a second hook. Both hooks carry the row's credentials, so both authenticate, and only the 60-second Redis key stops an event from being processed twice. Under the worker, this needs a run that housekeeping ended as stalled while its process kept running.
    7. The lease comment doesn't hold. CLAIM_LEASE says it's "twice the job's 300 s deadline". Neither the chart's gitlab-webhook-install CronJob nor the worker task sets a deadline. The impact is small, because the claim is refreshed before each create, but the comment should be fixed or a deadline added.

    Items 1–4 may be worth re-scoping now that #874 serializes runs. Items 5 and 6 still let duplicate hooks or duplicate deliveries happen without them.

    Acceptance criteria:

    • Two overlapping runs claim different rows. Items 5 and 6 above can still produce a second hook.
    • A run whose claim was taken over writes no row state (done in fix(gitlab): PLTF-3689 claim webhook rows and support hook repair #692); its hook gets 403 and is deleted at the next visit (not done: the hook shares the row's credentials, so it authenticates and isn't deleted).
    • A create that times out after GitLab made the hook doesn't leave a duplicate. fix(gitlab): PLTF-3689 claim webhook rows and support hook repair #692 does this by adopting the hook rather than creating one under a new intent and deleting the first.
    • The two visit-race criteria, the two legacy-conversion criteria, the "two authenticating hooks start one conversation" criterion, and the GitLab version checks. None are built.

    Dependencies: the claim columns landed in migration 177 (#681). gitlab_hook_intent and gitlab_delivery haven't been added.


    This comment was created by an AI agent (OpenHands) on behalf of @aivong-openhands, after reviewing main at 3590801.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions