Skip to content

feat: build pull requests on their head commit (per-project setting) - #1377

Open
skipi wants to merge 32 commits into
mainfrom
dk/pr-head-build-feat
Open

skipi wants to merge 32 commits into
mainfrom
dk/pr-head-build-feat

Conversation

@skipi

@skipi skipi commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

Adds a per-project setting for GitHub projects: build pull requests on GitHub's merge commit (default, unchanged) or on their head commit. In head mode a pull request builds refs/pull/N/head pinned to the head SHA, so the run no longer waits for GitHub's mergeable field, which on busy base branches can stay unknown for long enough that no pipeline starts. Jobs get SEMAPHORE_GIT_PR_BASE_SHA (the base-branch commit from the pull request event, or the current base tip for API-started runs) to diff or merge against the base themselves.

The change spans github_hooks (head-mode checkout, the new value, and the migration for the new project column), projecthub and its REST API (the setting), zebra (the environment variable), front (the settings toggle) and the MCP server. New proto fields: pull_request_commit (projecthub, 15) and pr_base_sha (repo_proxy, 28; 26 and 27 are taken by the sem-approve options). Deploy order: protos, github_hooks, projecthub and zebra, then front. The original implementation is by Dejan; this branch merges current main and leaves the public API v2 untouched.

Rollout order

  1. github_hooks first. Its migration adds projects.pull_request_commit. ProjectHub deployed before it fails every Describe, List, Create and Update call (missing column).
  2. ProjectHub, then ProjectHub REST API and Zebra (Zebra reads pr_base_sha, proto field 28 of the repo_proxy Hook).
  3. Front together with github_hooks, or before it. Head-mode pull requests no longer record pull_request_mergeable; only the new Front derives the conflict banner from the project's mode. An older Front reads the empty value as a conflict and shows a false "has conflicts" banner on head-mode pull requests.
  4. The pr_head_builds feature must exist and be enabled per organization before the project setting can be used. It is off by default (helm chart), and turning it off makes github_hooks build the merge commit again for every project.

Migration note: the column is added with raw SQL on purpose. The PostgreSQL adapter's add_column clears the prepared-statement cache first, and behind a transaction-pooling pgbouncer that sends DEALLOCATE to a different server connection and aborts the migration transaction.

Tested

On a non-production deployment of this branch:

  • With the feature off, a normal PR builds the merge commit (SEMAPHORE_GIT_SHA is the merge commit, SEMAPHORE_GIT_PR_BASE_SHA is set) and switching a project to head_commit is refused with "not available for this organization".
  • With the feature on and head_commit set through the REST API: a push builds the head (SEMAPHORE_GIT_SHA = SEMAPHORE_GIT_PR_SHA = head, base SHA set) within seconds, and a PR GitHub reports as conflicting builds too; its branch pull_request_mergeable stays NULL.
  • A run started through the API for refs/pull/N has a non-empty commit equal to the head.
  • Switching back to merge_commit builds the merge commit again; invalid values return 422 and an omitted field keeps the stored value.
  • Turning the feature off made github_hooks build the merge commit on the next push, with no restart.

Known gaps

  • The fallback path (refs/pull/N/head, used when GitHub refuses to create the pin) was not reproduced live: a PR touching .github/workflows/ was not refused. It, and /sem-approve after a fork push, are covered by specs only.
  • The mcp_server copy of the projecthub proto is not regenerated from the updated proto (it lacks the sem-approve fields as well).
  • ProjectHub's feature cache can lag behind a feature change by 30+ minutes (tracked separately), so after disabling the feature ProjectHub may keep accepting head_commit for a while; builds ignore it as soon as github_hooks sees the change.
  • Front conflict banner is covered by controller tests only.

🤖 Generated with Claude Code

dexyk and others added 6 commits October 28, 2026 07:52
The v2 RunType schema listed four of the five run types a project can have.
Describing or listing a project with draft pull request builds enabled
failed, and v2 clients could not send the value back on update.
Adds a per-project setting, pull_request_commit, that selects which commit
pull request workflows build: the merge commit (default, as before) or the
head commit of the pull request branch. Head commit builds skip GitHub's
mergeability check, so they start right away and also run for pull
requests with conflicts. GitHub projects only.

- projecthub, github_hooks: projects.pull_request_commit column. An
  unspecified value keeps the stored setting on update and means
  merge_commit on create; head_commit is rejected for non-GitHub projects.
- github_hooks: head commit builds for pull request events, /sem-approve
  and API-triggered pull request runs; hooks expose pr_base_sha.
- zebra: SEMAPHORE_GIT_PR_BASE_SHA in every pull request job.
- front: setting in the project's general settings.
- projecthub-rest-api (v1alpha) and public-api/v2: pull_request_commit in
  the project spec.
- mcp_server: shown in project details.
- docs: the setting, the project YAML property and the new variable.
Resolved conflicts with the sem-approve options change: the head-mode PR
paths keep the stale-head approval check (head_sha is returned), projecthub
keeps both validations, and the repo_proxy Hook field pr_base_sha moves from
26 to 28 because main now uses 26 and 27 for approval_include_secrets and
approval_enable_cache.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This reverts commit 856bf6d.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Restore public-api/v2 to origin/main. The pull_request_commit setting is
not exposed through the v2 API.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… runs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
skipi and others added 15 commits October 29, 2026 13:39
In head mode the fallback ref result carried head_sha but no commit_sha, so
API, CLI and scheduled pull request runs stored a nil commit and checked out
an empty SEMAPHORE_GIT_SHA.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e head ref can't be pinned

The fallback result echoed the workflow's own commit as the live head, so the
stale-head check compared the approval with itself and a fork push after a
bare approval ran unreviewed. The fallback now reads the pull request and
reports its current head.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…rgeable

Head builds fabricated pull_request_mergeable = true, which hid conflicts that
were never checked. github_hooks now leaves the column untouched for head-mode
projects (no write, no PullRequestUnmergeable event), and the branch page
derives the conflict banner from the project mode, since the column defaults
to NULL and would otherwise read as a conflict.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The project setting is offered in the UI only when the feature is on (or the
project is already on head commits), projecthub and the REST API ignore the
value when it is off, and github_hooks treats a head-mode project as merge mode
when the feature is off, which makes the feature the kill switch. Off by
default in the helm chart.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Drop the sem-ai --pull-request-commit flag, which doesn't exist, say that a
re-run can build a newer head when GitHub can't keep a reference, document
/sem-approve in head mode, mark SEMAPHORE_GIT_PR_BASE_SHA as GitHub-only, and
restore the blank line before the settings screenshot.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…st modes

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The sem CLI parses project YAML strictly, so the key would be rejected by
sem create, apply and edit. The setting is available in the project settings
page and the REST API.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…off, make the migration idempotent

Asking for head commit builds while pr_head_builds is off now fails instead of
silently returning OK; keeping an already stored head_commit value still
succeeds so settings saves don't break. The pull_request_commit migration
skips an existing column and sets a lock timeout.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…s stub

The stub replaced the whole feature list, so project creation failed on the
missing max_projects_in_org quota.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… banner workflow a pipeline

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…can't abort the migration

Rails' PostgreSQL add_column clears the prepared statement cache first, which
sends DEALLOCATE for statements prepared on another pgbouncer server
connection. The error is swallowed but aborts the DDL transaction, so the next
statement fails with InFailedSqlTransaction. Raw SQL skips the cache clear.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…anner page

The workflow list stub returns every workflow in insertion order, so the
banner was derived from an older branch workflow.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@skipi
skipi marked this pull request as ready for review October 30, 2026 12:07
Brings front's repo_proxy.pb.ex in line with internal_api Hook.pr_base_sha = 28,
as already present in the zebra stub.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@loadez loadez assigned skipi and unassigned DamjanBecirovic Nov 6, 2026
skipi and others added 5 commits November 9, 2026 10:09
pull_request_head_commit? asked the feature service on every call, and
a hook run asks up to four times. A lookup that failed partway through
could switch modes mid-run, for example recording a mergeable branch as
unmergeable after building its head commit.

The answer is now kept on the project for the rest of the run, so one
hook and one RepoProxy request see one mode and make one feature call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Head commit builds need both the stored setting and the pr_head_builds
feature. With the feature off, pull requests build the merge commit, but
front hid the conflict banner and the settings page still showed head
commit as active. projecthub also ignored a switch back to the merge
commit while the feature was off, so the project couldn't leave the
setting.

The conflict banner now checks the feature too, the settings page says
when head commit builds aren't available, and projecthub always accepts
the merge commit. Head commit stays gated as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The docs said /sem-approve in head commit mode refuses to run when the
pull request head changed after the approval. It runs the approved
commit, which is pinned, and only refuses when that commit can't be
pinned and the head moved. Say that, and cover the three cases with
specs: the pinned commit builds with its approval options after a later
push, and without a pinned ref a moved head is refused and an approval
with options is released.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Bitbucket payload's pr_base_sha is the pull request's own source
commit, so Bitbucket jobs got that commit as SEMAPHORE_GIT_PR_BASE_SHA.
The variable is documented for GitHub projects only, so RepoProxy now
fills it only for GitHub payloads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
skipi added a commit that referenced this pull request Nov 9, 2026
## 📝 Description

The `mcp_server` dependency check (`MCP Server: Deployment
Preconditions` → `Check dependencies`) fails on `main` because of a
newly published advisory, CVE-2026-78661 (HIGH), in `golang.org/x/net`
v0.60.0. This bumps the indirect pin to v0.62.0, which fixes it. `go mod
tidy` also moves `x/sync`, `x/sys` and `x/text` to the releases `x/net`
v0.62.0 requires. There is no code change, and the Go version and the
Dockerfile are unchanged.

Any PR that runs the MCP Server blocks is red until this lands, for
example #1377.

## ✅ Checklist
- [x] I have tested this change: `go build`, `go vet ./...` and `go test
./...` pass on `golang:1.26.9-alpine3.23`. The dependency check passes
locally on this branch and fails on `main`'s `go.mod` with the same
finding.
- [ ] This change requires documentation update

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
adbatista added a commit that referenced this pull request Nov 12, 2026
## 📝 Description

A pull request build checks out GitHub's test-merge commit
(`merge_commit_sha`). GitHub computes that commit asynchronously and can
report the PR as `mergeable: true` while still returning the test-merge
of an earlier head. Building it runs code that does not contain the
pushed commits, and reruns of that workflow keep the same commit.

This change enforces one invariant: **a PR build only runs on a merge
commit whose parents include the pushed head.**

### Change

- Before creating `refs/semaphoreci/<merge>`, `update_pr_data` reads the
merge commit's parents through the git data API (`GET
/repos/{repo}/git/commits/{sha}`, new
`RepoHost::Github::Client#git_commit`) and requires the expected head
among them:
- webhook-driven builds: the head from the webhook payload
(`webhook_head_sha:`, read from the payload rather than
`workflow.commit_sha`, which is overwritten with the merge SHA);
- `PrPayload` (gRPC), which has no webhook: the head from GitHub's PR
response.
- Parents are cached by repository and SHA in Redis (see below). A
failed or empty lookup is not cached.
- A merge without the expected head returns `:stale_merge_commit`, and
no ref is created for it. In the webhook path:
- **Superseded:** the merge holds GitHub's current head, and a hook
received within 30 minutes after this one for the same PR (matched by
`refs/pull/N/merge` or branch) has that head as its commit or already
built that merge. The workflow is marked `skip_superseded_pr` and
counted in `hook.processing.pr_superseded`; it is not retried. Commit
ancestry is not used: a push that resets the PR to an older commit is
still the newest push.
- **Stale:** otherwise the hook is rescheduled every minute up to
`STALE_MERGE_COMMIT_MAX_RETRIES` (default 5, sharing the
unknown-mergeability rate-limit reserve). The stale attempt count is its
own job argument, so reschedules for other reasons do not use up this
budget. Past the budget it ends in the new `pr_stale_merge_commit`
state.
- For `/sem-approve` launches, a stale merge whose live head no longer
matches the approved head ends in `pr_approval_stale`, as before;
otherwise the approval claim is kept across the reschedule.
- `PrPayload` raises `PrNotMergeableError` saying the merge commit is
not up to date yet.
- A `NotFound` / `Unauthorized` error while reading the merge commit is
treated as stale with reason `lookup_failed` and retried, instead of
marking the repository as not found / unauthorized.
- Observability: `pr-stale-merge-commit-rescheduled` / `-giving-up` and
`pr-superseded` logs go through the job's logger (with `workflow_id`)
and carry `reason`, both heads, the merge SHA and the stale attempt
count. Metrics are tagged with the reason:
`hook.processing.pr_stale_merge_commit` counts each hook once,
`..._attempt` counts attempts, `..._giving_up` counts give-ups, and
`hook.processing.pr_superseded` counts superseded hooks.

### One merge per PR event, shared by all projects on the repository

Every project connected to a repository receives the PR event and used
to resolve the test-merge on its own: up to 9 pull request polls, a
commit lookup, the parents lookup and a ref creation per project.
Besides the cost, a base branch moving mid-way left projects building
different merges for one push.

- The merge is now resolved once per PR event, keyed by repository, PR
number, webhook head and webhook base SHA (every delivery of one event
carries the same pair; a base branch change gets a new key).
- The key is also scoped to the organization and the credentials the
project uses: GitHub App projects share within an organization, OAuth
projects only with projects using the same user's token. A project whose
own access is gone therefore never builds a merge stored by another
project; it still ends as an unauthorized / not found repository.
- The first worker takes a Redis lock (30 s), resolves the merge as
above and stores it (1 hour, write-once). Other workers wait for it (up
to 20 s, polling every 0.5 s) and build the same merge without calling
GitHub. When the holder finds mergeability still unknown, that result is
kept as long as the lock and waiters return `:mergeable_unknown` at
once, so the usual 2-minute reschedule takes over instead of a second
poll. When the holder fails with a transient GitHub error (rate limit,
5xx, timeout, connection failure), that is kept as long as the lock too,
and the workers waiting on it raise `ServiceUnavailable` into Sidekiq's
retry instead of repeating its requests. Later attempts, the holder's
own retry included, do not read it and call GitHub again. When the
holder ends with another result (stale, skip-ci, conflict, a
non-transient error), or the wait runs out, they resolve it themselves
as before. Waiters re-read the result once the lock is gone, so a merge
stored just before its release is not missed.
- Only `:ok` results whose commit is the webhook head are stored.
`/sem-approve` launches never use the store, since they compare GitHub's
live head with the approved one; `PrPayload` has no webhook head and
does not use it either.
- Commit details (author, skip-ci) and merge parents are cached by
repository and SHA in the same store, so retries and other projects on
any worker hit them. These stay repository-scoped: they are only read
after the project's own pull request request succeeded.
- Each GitHub request of the PR path is bounded to 10 s
(`RepoHost::Factory.create_from_project(project, request_timeout:)`;
other callers keep Octokit's defaults), so a holder stuck on a slow
GitHub fails well within the lock instead of hanging on default
timeouts.
- The store is the Sidekiq Redis through its own small pool with 0.2 s
timeouts; the merge, unknown and failure results are read in one `MGET`.
Any Redis error reads as a miss, and a failure to take the lock skips
the wait instead of being read as a lock held elsewhere and is counted
in `github_hooks.shared_cache.error` (logged at most once a minute per
process), and `GITHUB_SHARED_CACHE_ENABLED=false` turns it off. Reuse is
counted in `hook.processing.pr_merge_shared` (`reused` /
`reused_unknown` / `reused_failure` / `stored`).

### Transient GitHub errors and `/sem-approve`

A resumed, already approved fork PR used to release its approval claim
on any error, so the worker's retry found it no longer in progress,
logged `pr-approval-resume-skipped` and built nothing. A resumed run now
keeps its claim through transient errors (rate limiting, 5xx including a
raw 502, timeouts, connection failures) so Sidekiq's retry launches it;
other errors still release it. The approval comment's own run still
releases on any error, because its retry claims the workflow again. When
Sidekiq exhausts its retries, the worker frees a claim that is still
held so a new `/sem-approve` can take it. Throttling stays on Sidekiq's
backoff rather than the stale budget, which would give up within
minutes.

### Reviewer notes

- **GitHub API cost:** the parents check adds one `GET
/git/commits/{sha}` for the worker that resolves a PR event. With 8
projects on one repository, a push that resolves on the first try goes
from roughly 40 requests (8 × poll + commit + parents + ref) to roughly
5; a retry wave goes from 32 to 4.
- **Worker time:** waiting workers hold a Sidekiq thread for up to 20 s,
comparable to the existing in-thread mergeability poll (about 12 s).
- **Superseding lookup cost:** the query is limited to a 30-minute
window, but `workflows` only has a `project_id` index, so on a large
project Postgres still filters that project's rows. Its plan is being
checked on a high-volume project; if it reads too many rows, a
concurrent `(project_id, created_at)` index follows in a separate
migration.
- **Remaining edge:** a manually redelivered older webhook is received
later than the push it describes and can count as the later hook.
- **Interaction with #1377 (build on head commit):** in head mode the
check must not run, since the ref points at the head commit itself.

## ✅ Checklist
- [x] I have tested this change
- Handler (`run`): merge containing the webhook head builds, also while
GitHub's head lags; a stale merge reschedules without creating its ref
even when the ref is new; reset to an ancestor while GitHub still shows
the previous head reschedules; later hook for GitHub's head, or one that
built the merge, marks the hook superseded with no reschedule; later
hooks on another PR, earlier hooks, or hooks received more than 30
minutes later do not count; budget exhausted or rate limit below the
reserve ends in `pr_stale_merge_commit`; merge lookup `NotFound`
reschedules without marking the repository gone; the check uses the
webhook head after `commit_sha` was set to the merge SHA.
- Stale merge signals: reason tags (`head_missing`, `lookup_failed`),
one per-hook count across attempts, and a stale budget independent of
earlier reschedules.
- `/sem-approve`: claim kept across a stale-merge reschedule; stale
merge after a new fork push ends `pr_approval_stale`; a resumed approval
keeps its claim through rate limiting, 503, 500, 502 and timeouts and
releases it on other errors; the approval comment's run still releases
on a transient error.
- Worker: retry and stale attempt counts are passed through; exhausted
Sidekiq retries release a held approval claim and leave other workflows
alone.
- `update_pr_data`: `PrPayload` path uses GitHub's head and returns
`:stale_merge_commit` without creating the ref; only the webhook head is
required when one is given; a refused lookup reports `lookup_failed`;
parents and commits read once per SHA and shared across projects
regardless of repository name case; skip-ci remembered; failed lookups
not cached; unavailable Redis counts as a miss; nothing touches Redis
when disabled.
- Shared merge: a stored merge is reused without GitHub calls and its
ref is created once; the first stored merge is kept; another base
resolves on its own; stale merges and merges for another commit are not
stored; the lock is released; a waiter takes the holder's merge,
resolves itself when the holder finishes without one, and stops after
the wait limit; a waiter takes a holder's unknown mergeability and
reschedules without requesting the PR; a holder's transient error is
recorded for the workers waiting on it, a waiter fails when the holder
reports one, a later attempt calls GitHub again, and non-transient
errors are not recorded; an unavailable Redis never makes a worker wait;
the PR path builds its client with the request timeout; and takes a
merge stored just before the lock is released; sharing within an
organization for GitHub App projects, not across organizations or
between different OAuth users; no sharing without a webhook base; `run`
builds a merge another project stored; approval launches pass no base; a
commit GitHub did not return is not cached.
- `GithubCache`: round trip, TTL, write-once, token-checked lock
release, multi-key read, fail-open with a metric (lock errors reported
apart from a held lock), error log throttling, one pool across threads,
disabled.
- `PrPayload` raises for `:stale_merge_commit`; client specs for
`#git_commit` and the optional request timeout; factory passes the
timeout through.
- Full github_hooks suite: 1033 examples; the only failures are 4
pre-existing `pending` specs in `client_spec.rb` that pass locally.
RuboCop: no offenses.
- [ ] This change requires documentation update
adbatista pushed a commit that referenced this pull request Nov 17, 2026
## 📝 Description

The `mcp_server` dependency check (`MCP Server: Deployment
Preconditions` → `Check dependencies`) fails on `main` because of a
newly published advisory, CVE-2026-78661 (HIGH), in `golang.org/x/net`
v0.60.0. This bumps the indirect pin to v0.62.0, which fixes it. `go mod
tidy` also moves `x/sync`, `x/sys` and `x/text` to the releases `x/net`
v0.62.0 requires. There is no code change, and the Go version and the
Dockerfile are unchanged.

Any PR that runs the MCP Server blocks is red until this lands, for
example #1377.

## ✅ Checklist
- [x] I have tested this change: `go build`, `go vet ./...` and `go test
./...` pass on `golang:1.26.9-alpine3.23`. The dependency check passes
locally on this branch and fails on `main`'s `go.mod` with the same
finding.
- [ ] This change requires documentation update

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
skipi and others added 2 commits November 26, 2026 12:56
Conflicts in the github_hooks hook handler and its spec, where main
added the shared merge commit per pull request event, the stale merge
commit check and the ready_for_review /sem-approve fix:

- update_pr_data returns the head commit result before any shared
  merge lookup, so head commit builds keep skipping the test merge,
  its cache and its stale check.
- Both sides' specs are kept.

This branch had renamed the merge commit in the update_pr_data result
from :merge_commit_sha to :commit_sha. Main's shared merge code still
read and returned the old key, so a merge reused from another worker
reached the workflow without a commit SHA. The shared result now
carries :commit_sha; the value stored in the cache keeps its
"merge_commit_sha" field, so workers of both versions read each
other's entries during a rollout. Specs of main that built a Project
double or read the old key are adapted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The approval specs' stubbed update_pr_data result still used the
merge commit key from before the rename to :commit_sha, so the
ready_for_review approval specs launched a workflow without a commit
SHA and still passed. The stub now uses :commit_sha, and the
ready_for_review launch spec checks the launched commit.

The /sem-approve options section said a run only starts if the named
commit is still the pull request head; with the head commit option the
named commit runs even after newer pushes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

3 participants